Arraylist.clear 清除所有数组列表? [英] Arraylist.clear clearing all array lists?

查看:34
本文介绍了Arraylist.clear 清除所有数组列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 2 个单独的数组列表.一个叫 spawnList,另一个叫 foundList

I have 2 separate array lists. one called spawnList and another called foundList

我运行了代码,它生成一个实体并将所述实体 ID 添加到 spawnList,所以现在 spawnList.size() 将等于 1

I have the code run through, it spawns an entity and adds said entity ID to the spawnList, so now spawnList.size() will equal 1

接下来运行它会清除 foundList 搜索实体并将它找到的内容与 spawnList 进行比较,任何匹配项都会添加到 foundList.

Next run through it clears the foundList searches for entities and compares what it found to the spawnList, any matches are added to the foundList.

我遇到的奇怪问题是当 foundList 被清除时 spawnList 也被清除

the weird issue I am having is when the foundList is cleared so is the spawnList

我缩小范围并打印出来进行测试

I narrowed it down and put some print outs to test

        System.out.println("spawnList = " + this.spawnList.size());
        this.foundList.clear();
        System.out.println("spawnList = " + this.spawnList.size());

这将打印出来

spawnList = 1
spawnList = 0

为什么在清除foundList时清除spawnList?

Why is the spawnList being cleared when the foundList is being cleared?

推荐答案

你写过代码吗

spawnList = foundListfoundList = spawnList ?

如果是这样,由于 ArrayList 是一个对象,您实际上并未复制这些列表,因此您使它们引用了相同的对象.(即你对一个人所做的一切都会对另一个人做).

If so, since an ArrayList is an object you weren't actually copying those lists, you were making them reference the same object. (IE everything you do to one will be done to the other).

如果您想减轻这种情况而不是直接将列表设置为彼此相等,您可以执行类似

If you want to mitigate against this instead of directly setting the lists equal to each other you could do something like

foundList = new ArrayList<>(spawnList)

因为这将使两个数组成为单独的对象.

as this will make the two arrays be separate objects.

根据数组中的对象类型,这仍然可能是一个问题,因为它们仍然是每个对象的相同实例.

Depending on what type of objects are in your arrays this could still be a problem, as they would still be the same instances of each object.

这篇关于Arraylist.clear 清除所有数组列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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