mercredi 14 avril 2021

Creating Objects dynamically at runtime with possible member values

I have a class of which objects I want to get instantiated at runtime and stored in a collection of such objects. However, the number of such objects can be dynamic in nature.

Let say,

class Car{
    private Color color;
    private Brand brand;
    //AllArgsConstructor
}

enum Color{
   RED, BLUE
}

enum Brand{
   VW, SUZUKI, HONDA
}

Now I want objects with all UNIQUE possible permutations from 2 enums(in this case 2*3 = 6) to be created at runtime and added to a collection.

If I were to do this manually, I would do:

Car carRV = new Car(Color.RED, Brand.VW);
Car carRS = new Car(Color.RED, Brand.SUZUKI);
Car carRH = new Car(Color.RED, Brand.HONDA);
Car carBV = new Car(Color.BLUE, Brand.VW);
Car carBS = new Car(Color.BLUE, Brand.SUZUKI);
Car carBH = new Car(Color.BLUE, Brand.HONDA);

//addToCollection

But the problem with the above is too much coding and very manual to keep on adding as a new enum value is added. Is there a better way to do this?

Thanks in advance :)

Aucun commentaire:

Enregistrer un commentaire