b*********n 发帖数: 1258 | 1 发现一个 ArrayList 很奇怪的现象
一个 ArrayList X
和一个 ArrayList> Y
想要实现: Y = [X, X]
ArrayList X = new ArrayList();
ArrayList> Y = new ArrayList>();
X.add(Double.valueOf(0)); // 先set X
X.add(Double.valueOf(1));
Y.add(X); // 把 X 加入 Y
System.out.println(Y);
X.set(0,Double.valueOf(0.5)); // 然后修改 X :
X.set(1,Double.valueOf(1.5));
Y.add(X); // 再把 X 加入 Y
System.out.println(Y);
应该是第一次打印的 Y 是 : [[0, 1]]
第二次打印的 Y 是 : [[0, 1], [0.5, 1. | P********e 发帖数: 2610 | 2 That's exactly, why I said, clone method should be on the textbook.
It's pass by value, reference in Java, you did not really create an new
object and add to the Y, you added the reference to the Y.
Do this:
Y.add(X.clone()); //physically clone a copy of X and add it to Y, rather
than reference.
each time.
You'll get what you want.
【在 b*********n 的大作中提到】 : 发现一个 ArrayList 很奇怪的现象 : 一个 ArrayList X : 和一个 ArrayList> Y : 想要实现: Y = [X, X] : ArrayList X = new ArrayList(); : ArrayList> Y = new ArrayList>(); : X.add(Double.valueOf(0)); // 先set X : X.add(Double.valueOf(1)); : Y.add(X); // 把 X 加入 Y : System.out.println(Y);
| b*********n 发帖数: 1258 | 3 wow!
这下出来了
太谢谢了!
【在 P********e 的大作中提到】 : That's exactly, why I said, clone method should be on the textbook. : It's pass by value, reference in Java, you did not really create an new : object and add to the Y, you added the reference to the Y. : Do this: : Y.add(X.clone()); //physically clone a copy of X and add it to Y, rather : than reference. : each time. : You'll get what you want.
|
|