Java and ArrayList - really simple fix i think, please help

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:
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
 
ok your method works but then I'm stuck as to what to do. the problem is I don't know how many objects I'm going to have (they're going to be read from a file), so I was just going to look out for the word "sheep" for example, and then call the code to add it to the list.

is there a way i can add a new variable everytime that has a number in it thats always one more than the previous? (i.e. if a Sheep5 exists then the next one should be Sheep6).
 
the data will be coming from an external txt file, but i haven't implemented that yet.

the file is just going to have the list of the animals, with the first argument being the animal type, the next tag, and s on:
Sheep 1
Sheep 2

but i don't know how many sheep there will be.

your code looks good but i still can't see how i can just append a new sheep into the list. i thought once you stored a variable into an arraylist, the variable can be destroyed as all the information is at arraylist(index).
 
Back
Top Bottom