如何在不使用“new”关键字且不修改原始列表的情况下返回新列表?

问题描述 投票:0回答:1

我正在使用 Java 中的一个简单的

IntList
类。

public class IntList {
    public int first;
    public IntList rest;

    public IntList(int f, IntList r) {
        first = f;
        rest = r;
    }

对于给定的

IntList
,我需要一个方法
incrList
,它将把
L
的所有成员增加
x
,同时不修改
L
。这是我的解决方案:

public static IntList incrList(IntList L, int x) {
        IntList newList;
        if (L.rest == null) {
            newList = new IntList(L.first + x, null);
        } else {
            newList = new IntList(L.first + x, incrList(L.rest, x));
        }
        return newList;
    }

我已经意识到这可以在没有

new
关键字的情况下完成,但我什至不知道在不创建新对象的情况下从哪里开始。

java methods pass-by-reference variable-assignment
1个回答
0
投票

CS61A Sp16 讲义的答案

first = head
rest = tail
public static IntList dincrList(IntList L, int x) {
        /** Using recursion, but iteration also works. */
        if (L == null) {
            return null;
        }

        L.head = L.head + x;
        /* Don't actually care about the return value here. */
        dincrList(L.tail, x);

        return L;
    }
© www.soinside.com 2019 - 2024. All rights reserved.