简体   繁体   中英

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.

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());
        }    
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM