简体   繁体   English

Arraylist.clear清除所有数组列表?

[英]Arraylist.clear clearing all array lists?

I have 2 separate array lists. 我有2个单独的数组列表。 one called spawnList and another called foundList 一个叫做spawnList,另一个叫做FoundList

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

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进行比较,所有匹配项都会添加到foundList中。

the weird issue I am having is when the foundList is cleared so is the spawnList 我遇到的奇怪问题是当foundList被清除时,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());

This will print out 这将打印出来

spawnList = 1
spawnList = 0

Why is the spawnList being cleared when the foundList is being cleared? 为什么清除foundList时会清除spawnList?

Have you ever wrote the code 你写过代码吗

spawnList = foundList or foundList = spawnList ? spawnList = foundListfoundList = spawnList吗?

If so, since an ArrayList is an object you weren't actually copying those lists, you were making them reference the same object. 如果是这样,由于ArrayList是一个对象,您实际上并没有在复制这些列表,因此您使它们引用了同一对象。 (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. 取决于数组中对象的类型,这仍然可能是一个问题,因为它们仍然是每个对象的相同实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM