John of York John of York - 5 months ago 10
Java Question

How do I create multiple objects in Java?

Couldn't be simpler. In Android Studio I have a class called

Dog
and I simply wish to create numerous
Dog
objects. I can do it as shown below but I guess there's a much less tiresome way. Is there?

final Dog buster = new Dog();
final Dog rover = new Dog();
final Dog fido = new Dog();
// and more


Thanks guys.

Answer

This might be an amusing way to do it:

public enum DogName {
    buster, rover, fido
}

....
EnumMap<DogName,Dog> dogs = new EnumMap<DogName,Dog>();
for (DogName name : DogName.values()) {
    dogs.put(name, new Dog());
}    

This compiles:

import java.util.EnumMap;

class Dog {
    public enum DogName {
        buster, rover, fido
    }

    private static final EnumMap<DogName,Dog> dogs = new EnumMap<>(DogName.class);
    static {
        for (DogName name : DogName.values()) {
            dogs.put(name, new Dog());
        }    
    }
}
Comments