-
Java: ArrayLists
Hey there,
I am trying to use an ArrayList to store my user-defined objects yet I keep coming up with the same problem...
Code:
public static void main()
{
ArrayList list = new ArrayList();
list.add(new item("Fred", 100));
list.add(new item("Jim",200));
System.out.println(((item)(list.get(0)).getIdentity());
}
When I run that code, the output is...
JIM
but of course is should be fred, is this a problem with referencing, it seems like the last item I add is overwriting the reference or data of the object(s) in the list. Can anyone suggest a solution or at least an explanation of the problem.
Freddy_no_nose.
-
Works fine for me.
Delete all .class files and recompile everything.
-
Hey there,
I just tried it and unfortuantly it didnt work. Could there be another reason for this. Lee.
-
Try copying your .java files (not the .class files) into another directory, then compile and run from there.
-
Sorry, no luck.
Im building an example of the problem now.
-
1 Attachment(s)
Heres the test, with the same result. Lee
-
Take your Java book and learn what the static keyword means...
-
What java book :)
Ok, Ill take a look. Thanks.
-
I agree with cornedbee...
Is your item class possibly be static in your declaration? since you did not include the item class I'm not quite sure though, but the problem really lies there..static is the keyword. :D
-
Yes, the data members are static in the zip file.
Which, btw, means that they exists only once and are shared between all instances of the class. What you write out is actually the first class instance, but as all of them share the same data the second constructor call has simply overwritten it.