0

I need to create multiple objects in a loop. I read elsewhere that adding them into a list would accomplish this task, but the below code gives me a set of copies of the same object, i.e. all with the same values. Any idea how I can create multiple objects, rather than just copies of the same one? Thank you.

(The code below is a simplified version of what I'm working on)

    System.out.println("Creating swarm of size "+swarmSize);
    List<Dog> myDogs = new ArrayList<Dog>();

    for(int i = 0; i < dogAmount; i++) {
        System.out.println("New Dog # "+i);
        myDogs.add(new Dog(i));
    }

    Dog first = myDogs.get(0);
    Dog other = myDogs.get(3);
    System.out.println(first.getID()+" "+other.getID());
    //prints out the number of dogs I should have created -1 both times

My Dog class

import java.util.*;

public class Dog{
    public static int dogID;

    public Dog(int ID) {
        dogID = ID;
    }

    public int getID() {
    return dogID;
    }

    public void setID(int id) {
        dogID = id;     
    }
}
1
  • 1
    could you paste the code for class Dog please? Commented May 5, 2013 at 3:49

2 Answers 2

5

Change

public static int dogID;

to

public int dogID;

or better yet,

private int dogID;

since you have a getter function for it, so other classes don't need to access the field directly.

Sign up to request clarification or add additional context in comments.

Comments

1

You're using:

public static int dogID;         //STATIC is the issue

Which means that all dogs have the same dogID, try to remove 'static' and it will work. (Every dog will have a unique ID).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.