Suhyeon Lee Suhyeon Lee - 1 month ago 9
Java Question

JAVA: How can I initialize an ArrayList to specific class type with Object-wrapped instance?

Let's say we have 2

class
types below:


class Cola {}
class Milk {}


And an
Object
instance which type is one of above classes:

public Object getDrink(boolean random){
if(random)
return new Cola();
else
return new Milk();
}
Object drink = getDrink(random);


Of course I can check the class of
drink
by calling
drink.getClass()
or
drink.getClass().getCanonicalName()
or so. That's ok.



My problem is that, I want to make and initialize an ArrayList of
drink
class type, NOT
Object
type.


ArrayList<Object> list // This is NOT what I want.
ArrayList<drink.getClass()> list2 // Exactly what I want (but not right)




How can I do this?

Answer

Create an interface called Drink

In both Cola and Milk implement the interface Drink

Store as ArrayList <Drink> list;