java - 有人能告诉我为什么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)
解决方案
如果您不想修改 IntList,请先将字段设置为最终字段,以便它们一旦设置就无法更改。
catenate 方法需要复制 A,所以它不会修改原始列表。
为此,请按照您的操作循环列表,但在每一步保存值(在另一个 IntList 或另一个结构(如 ArrayList)中。然后,一旦您获得最后一个值,创建一个新的 IntList,第一个作为A 中的最后一个值,其余为 B。
new IntList(L.first, B);
现在循环浏览您从 A 中保存的项目,以相反的顺序将它们添加到这个新列表中。
推荐阅读
- javascript - 从 AWS-S3 存储桶访问我的应用程序
- python - 使用 Python 查找 Excel 单元格值 0
- mysql - MySQL 如何将列转换为行?
- distributed-system - Google Spanner 可以用 Raft 代替 TrueTime 实现吗?
- javascript - 根据值减少的对象数组
- python - Python GTK:label.set_text() 不能按预期工作
- nan - 当没有找到 nan 值时,平均值怎么可能是 nan?
- dns - 在 SiteGround 中购买域会出错
- java - (java) 更改文件后如何更新 BufferedReader
- c++ - 为什么我的 HID 键盘不能很好地工作?