ArrayList.add()在一个循环之后,所有的元素都相同。为什么?

编程入门 行业动态 更新时间:2024-10-17 19:22:50
本文介绍了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()在一个循环之后,所有的元素都相同。为什么?

本文发布于:2023-11-06 23:49:47,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1564998.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:元素   ArrayList   add

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!