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

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

问题描述

如果我这样做[quasi-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天全站免登陆