Associate
- Joined
- 21 May 2003
- Posts
- 1,008
Hi there. I'm trying to use an ArrayList to add different objects (in this case Animals). each Object can be a specific type (in this case Sheep), and each individual object has its own values (i.e. there can be many Sheep but they all have their own tag).
when I use the code below, I can add an object fine, but when I add another Object that is the same type, all the details of previously added objects change to the one being entered. i.e from the code below I get:
So the first object was added and the tag was 1, but when i added the second, the tag became 2 for the first object as well. why is this? it's like "tag" is set to static but it isn't.
heres the code (the two for loops are just to print out the tags for debugging):
Any help is appreciated
when I use the code below, I can add an object fine, but when I add another Object that is the same type, all the details of previously added objects change to the one being entered. i.e from the code below I get:
Code:
Object Added: 0 Tag 1
Object Added: 0 Tag 2
Object Added: 1 Tag 2
So the first object was added and the tag was 1, but when i added the second, the tag became 2 for the first object as well. why is this? it's like "tag" is set to static but it isn't.
heres the code (the two for loops are just to print out the tags for debugging):
Code:
import java.util.*;
abstract class Animal {
public abstract int get_tag();
}
class Sheep extends Animal {
int tag;
public void Sheep(int t){
tag = t;
}
public int get_tag(){
return tag;
}
}
public class NativityScene {
public static void main(String[] args) {
List<Animal> animals = new ArrayList<Animal>();
Sheep sheep = new Sheep();
sheep.tag = 1 ;
animals.add(sheep);
int num_objects = animals.size();
for (int j = 0; j<num_objects; j++){
System.out.println("Object Added: "+j+" Tag "+animals.get(j).get_tag());
}
sheep.tag = 2 ;
animals.add(sheep);
num_objects = animals.size();
for (int j = 0; j<num_objects; j++){
System.out.println("Object Added: "+j+" Tag "+animals.get(j).get_tag());
}
}
}
Any help is appreciated