ArrayList.add()在一个循环之后,所有的元素都相同。为什么? [英] After ArrayList.add() in a loop, all elements are identical. Why?

查看:612
本文介绍了ArrayList.add()在一个循环之后,所有的元素都相同。为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我这样做[准基于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()在一个循环之后,所有的元素都相同。为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆