Do all An ArrayList elements change when a new one is added?

First of all, apologies for the inability to provide any source code. My project is quite large, and connecting everything would be impractical, and I could not reduce the problem, which is extremely annoying. I will do my best to explain it here.

I dynamically create new instances of the class in every loop in my code. This instance dynamically sets a pair of properties, while in a loop, for example, "name". At the end of each loop, the newly created instance is added to the ArrayList, which is in another, third class.

However, the problem is that when you add a new element for any reason, all previous elements change in accordance with the latter. I assume that ArrayList creates a link to a dynamically created element, so that whenever it changes, they all change, but I don’t know how to fix it.

I would be grateful for any advice and apologies for the quality of this explanation. I will post any specific piece of code that you might want to see

As requested - XmlHandler.java - http://pastebin.com/mGmWt1RD ParsedDataSet.java = http://pastebin.com/k1xb3KBe Content.java = http://pastebin.com/UxiL2f9q

Just to shorten your understanding. The project is a reader of epics. The XMLHandler is called from the SAX parser in another class that is not shown. XMLHandler is used 3 different times for 3 different sets of XML, so there is some kind of mess.

The problem is the "toc" ArrayList. "Toc" or TableOfContents contain instances of content that will be referenced later (not shown). I try to pass data to every new instance of "Content" and then pass this to a static ArrayList array

+6
source share
2 answers

I have seen people repeatedly report this problem, and it always comes down to the following: in fact, you are not creating a new instance, but instead using the same one for each iteration of the loop. This is easy to do, especially if you come from a language with different semantics. There are many different ways to make this mistake; if you edit your question to show the loop code, I'm sure I can explain what is happening.

OK, now that you have added the code: the problem is that in the "Content" all data members are marked as "static". In Java, this means that there is one variable shared by all objects - i.e. The variable has the same value for each object. So in fact you are creating many Content objects to place in an ArrayList, but they all look the same! Remove these β€œstatic” attributes from the content data items and everything will be set.

+18
source

ArrayList just keeps a reference to the elements. Make sure your code looks like this:

 ArrayList list = new ArrayList<>(); loop(...) { MyObject newOne = new MyObject(); newOne.setXXX(xxx); list.add(newOne); } 

Incorrect code:

 ArrayList list = new ArrayList<>(); MyObject sameOne = new MyObject(); loop(...) { sameOne.setXXX(xxx); list.add(sameOne); } 
+10
source

Source: https://habr.com/ru/post/885588/


All Articles