【问题标题】:How can I change an Object instance and return a value from in the same method?如何更改 Object 实例并从同一方法中返回值?
【发布时间】:2020-10-08 20:44:56
【问题描述】:

我在使用自定义对象处理特定方法时遇到问题:

我创建了一个类“NodeQueue”,其中包含一个节点列表 (SList)、它的长度和列表的第一个元素

private final SList<Node> q;
private final int length;
private final Node first;

public NodeQueue()                              //Empty queue
{
    q      = new SList<Node>();
    length = 0;
    first  = null;
}

public NodeQueue(SList<Node> q1)             //Full queue
{
    q      = q1;
    length = q.length();                     //length() is the method that returns the length of SList<T>
    first  = q.car();                        //car() is the method that returns the first element of SList<T>
}

public Node poll()
{
    ...

    return first;
}

其中 poll() 的预期函数如下:

NodeQueue n = new NodeQueue();  //Let's pretend n is not empty

Node a = n.poll();              //Where "a" is the first element of the list

问题在于,在“poll()”中,我需要返回第一个元素(在本例中为节点 a)并将其从“NodeQueue n”的实际实例中删除。

我应该如何更新 Nodequeue 并在单个函数中返回第一个元素?

我基本上需要将“Node a”设置为NodeQueue的第一个元素,并将“NodeQueue n”设置为自身减去第一个元素。

【问题讨论】:

    标签: java object methods instance


    【解决方案1】:

    你会..只是..去做。

    public class Example {
        private int field;
    
        public int changeAndReturnSomething(int in) {
            this.field += in; //I changed a field...
            return in * 2; // and I return something!
        }
    }
    

    看起来微不足道。

    【讨论】:

    • 但是 q 有一个 final 属性,我只能用构造函数来改变,长度和第一个值取决于 q。
    • 我需要使用构造函数来更改所有内容,但我无法在该方法中启动它,因为我需要返回值为“first”。
    • 方法不能返回两个东西;您的 NodeList 结构是不可变的,因此无法更新。我猜你想要一个方法来返回删除的节点和新的节点列表(删除的节点不再在其中)。从一种方法返回 2 个东西是很棘手的;我建议你找到另一个设计。例如,这里没有不可变的数据结构。
    猜你喜欢
    • 2016-08-30
    • 2013-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-10
    • 1970-01-01
    相关资源
    最近更新 更多