Reputation: 1
I made a test program because I am trying to get back into Java after working in PL/SQL. I created a class Numbers that contains an integer, a getter and a setter. I have another class Test that is creating an instance of Numbers, and also adds that instance to a List. I created a for loop that loops two times and sets the value of the integer in Numbers equal to i. I then add that instance of Numbers to the List numbersList. I then do a print screen of the value that was added to the List. I do a total of 3 prints, one print the first time through the loop that prints the first position in the List, then I print two times during the second time through the loop,the first position in the List again, and the second position in the List. I was expecting to get 0,0,1 as the result. I am getting instead 0,1,1 as the result and I cannot figure out why. I am not changing anything in the first position in the List (numbersList[0]) during the second time through the loop, all I am doing is adding an instance of Numbers into the second position in the list (numbersList[1]).
import java.util.ArrayList;
import java.util.List;
public class Tests {
static int x;
public static void main(String[] args) {
List<Numbers> numbersList = new ArrayList<Numbers>();
Numbers numbers = new Numbers();
Numbers numbers2 = new Numbers();
for (int i = 0; i < 2; i++) {
if (i == 0) {
numbers.setVariable(i);
numbersList.add(numbers);
System.out.println(numbersList.get(0).getVariable());
}
if (i > 0) {
numbers2.setVariable(i);
numbersList.add(numbers2);
System.out.println(numbersList.get(0).getVariable());
System.out.println(numbersList.get(1).getVariable());
}
}
}
}
public class Numbers {
public static int a = 5;
public static void setVariable(int b) {
a = b;
}
public static int getVariable() {
return a;
}
}
Upvotes: 0
Views: 37
Reputation: 201429
Your class Numbers
has no instance fields (everything is static
, or class level).
It should look something like (and overriding toString()
is a good idea),
public class Numbers {
public int a = 5;
public void setVariable(int b){
a = b;
}
public int getVariable(){
return a;
}
@Override
public String toString() {
return String.valueOf(a);
}
}
By overriding toString()
you can more easily print instances of Numbers
. For example,
System.out.println(numbersList);
Upvotes: 1
Reputation: 53809
public static int a = 5
means that all instances of Numbers
share the same variable because of the static
keyword.
Therefore, when you do numbers2.setVariable(i);
, the variable is also changed for numbers
. Hence the 0,1,1
If you want instance variables remove the static
keywords from Numbers
.
Upvotes: 4