如果我这样做[准基于Java code]:
If I do this [quasi-java-code]:
while (loop) { localObject = getDataForObject(); globalPublicStaticArrayList<Object>.add(localObject); }
所有globalPublicStaticArrayList的元素是相同的,等于localObject的最后一个副本,添加。我踩通在调试器中循环,发现只要一个对象被添加,它被复制到globalPublicStaticArrayList的所有元素。
All the elements in globalPublicStaticArrayList are identical, equal to the last copy of localObject added. I stepped thru the loop in the debugger and saw that as soon as an Object is added, it is copied in to all the elements of the globalPublicStaticArrayList.
我找到的解决方法是:
while (loop) { localObject = getDataForObject(); globalPublicStaticArrayList<Object>.add(new Object(localObject.member1, localObject.member2,...)); }
有它是与通行证通过引用在Java中?为什么元素是在第一种情况相同?谢谢你。
Has it something to do with pass-by-reference in Java? How come the elements are identical in the first case? Thanks.
推荐答案Java使用按值调用,但在这里,这些值的引用的对象。
Java uses call by value, but here those values are references to objects.
什么要添加到列表中是不是对象的副本,但引用的副本。你的方法每次调用时都会返回同一个对象。它可能应该每次都返回一个新的对象,那么你就不会需要这个解决办法。
What you are adding to the list is not a copy of the object, but a copy of the reference. Your method returned the same object each time you called it. It probably should return a new object each time, then you wouldn't need this workaround.
更多推荐
ArrayList.add()在一个循环之后,所有的元素都相同。为什么?
发布评论