Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have 2 separate array lists. one called spawnList and another called 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

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.

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());

This will print out

spawnList = 1
spawnList = 0

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
286 views
Welcome To Ask or Share your Answers For Others

1 Answer

Have you ever wrote the code

spawnList = foundList or foundList = spawnList ?

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...