首页 > 解决方案 > 有人能告诉我为什么A也改变了吗?

问题描述

返回由 A 的元素后跟 B 的元素组成的列表。不得修改 A 的项目。使用“新”。IntList外观是这样的。

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

    public IntList(int first, IntList rest) {
        this.first = first;
        this.rest = rest;
    }
}

public static IntList catenate(IntList A, IntList B) {
    //TODO:  fill in method
    IntList C = new IntList(A.first, A.rest);
    IntList L = C;
    while(L.rest != null) {
        L = L.rest;
    }
    L.rest = B;
    return C;
}

我不知道为什么最后A也变成了C。下面是测试。

public void testCatenate() {
    IntList A = IntList.list(1, 2, 3);
    IntList B = IntList.list(4, 5, 6);
    IntList exp = IntList.list(1, 2, 3, 4, 5, 6);
    assertEquals(exp, IntList.catenate(A, B));
    assertEquals(IntList.list(1, 2, 3), A);
}

结果是

java.lang.AssertionError: 
Expected :(1, 2, 3)
Actual   :(1, 2, 3, 4, 5, 6)

标签: java

解决方案


如果您不想修改 IntList,请先将字段设置为最终字段,以便它们一旦设置就无法更改。

catenate 方法需要复制 A,所以它不会修改原始列表。

为此,请按照您的操作循环列表,但在每一步保存值(在另一个 IntList 或另一个结构(如 ArrayList)中。然后,一旦您获得最后一个值,创建一个新的 IntList,第一个作为A 中的最后一个值,其余为 B。

new IntList(L.first, B);

现在循环浏览您从 A 中保存的项目,以相反的顺序将它们添加到这个新列表中。


推荐阅读