Reputation: 307
public static void main(String[] args) {
// TODO Auto-generated method stub
List<item> l = new ArrayList<item>();
List<Integer> ll = new ArrayList<Integer>();
for (int i = 0; i < 10; i++) {
l.add(new item(i,i));
ll.add(i);
}
System.out.println(l.get(4).getWeight());
System.out.println(ll.get(4));
}
public class item {
private static int value;
private static int weight;
public item(int val, int w) {
setValue(val);
setWeight(w);
}
public static int getValue() {
return value;
}
public static void setValue(int value) {
item.value = value;
}
public static int getWeight() {
return weight;
}
public static void setWeight(int weight) {
item.weight = weight;
}
}
This is my code, and then item is class take two paratemers. But when I add the item into list, the elelments in list have same value(in this case it is 9). For Integer, there is no problem. I think I miss some critical parts of java feature.
Any help appreciated, thank you in advance.
Upvotes: 0
Views: 66
Reputation: 40436
All of your methods and members of item
are static
. That is, they belong to the item
class, rather than a specific instance of that class. The static
members are shared among every instance of the class, and so every new item
you create is using the same set of data. You will want to make them not be static
.
Check out the following official tutorials for more info, they are concise and well-written and will help you:
static
class members: Understanding Class MembersOnce you have done this, as Takendarkk astutely points out in a comment, be sure to use this.value = ...
instead of item.value = ...
(no longer valid) or value = ...
(uses local scope value
instead of member).
Upvotes: 10