I having trouble storing objects in an ArrayList.
I want to populate an ArrayList with a simple object called Variable. It has 2 string attributes: name and value. The problem is when I add a new Variable object to the list, the attributes of the previously added Variable objects appear to be null. Also, instead of being added to the end of the list, the new object is inserted at the first position.
Here is the code :
ArrayList<Variable> variables = new ArrayList<Variable>();
Variable author = new Variable();
author.setName("Author");
author.setValue("lusyo");
variables.add(author);
System.out.println(variables.get(0).getName());
Variable scenario = new Variable();
author.setName("Scenario");
author.setValue("Login");
variables.add(scenario);
System.out.println(variables.get(0).getName());
System.out.println(variables.get(1).getName());
The output is :
Author
Scenario
null
As you can see, scenario is located at index 0, but it should not be. I can’t figure out what’s going on with this code.
Thank you in advance for your help !
Does anything disturb you there?
:)