[英]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
类型:
class Cola {}
class Milk {}
And an Object
instance which type is one of above classes: 还有一个类型为上述类之一的
Object
实例:
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. 当然,我可以通过调用
drink.getClass()
或drink.getClass().getCanonicalName()
来检查drink
的类别。 That's ok. 没关系。
My problem is that, I want to make and initialize an ArrayList of drink
class type, NOT Object
type. 我的问题是,我想创建并初始化一个
drink
类类型而不是Object
类型的ArrayList。
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? 我怎样才能做到这一点?
Create an interface called Drink
创建一个名为
Drink
的界面
In both Cola
and Milk
implement the interface Drink
在
Cola
和Milk
实现接口Drink
Store as ArrayList <Drink> list;
存储为
ArrayList <Drink> list;
创建一个Drink
界面,修改Cola
和Milk
以implements Drink
,然后可以使用List<Drink> list2
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.