简体   繁体   English

JAVA:如何使用对象包装实例将ArrayList初始化为特定的类类型?

[英]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 ColaMilk实现接口Drink

Store as ArrayList <Drink> list; 存储为ArrayList <Drink> list;

创建一个Drink界面,修改ColaMilkimplements Drink ,然后可以使用List<Drink> list2

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何调用Java中存储在arraylist中的特定对象的方法? - How can I call a method of a specific object that is stored in an arraylist in Java? 如何从Java中的arraylist返回特定的对象(索引)? - How can I return a specific object (index) from an arraylist in Java? 我如何在Java中搜索类类型的数组列表 - How can i search an arraylist of a class type in java 在Java中,如何检查集合是否包含特定类的实例? - In Java, how can I check if a collection contains an instance of a specific class? 如何创建and抽象类的数组,以便可以将其初始化为特定的非抽象类(java) - How can I create an array of and Abstract class such that I can initialize it to a specific non-abstract class (java) 如何在 Java 中用全零初始化 ArrayList? - How can I initialize an ArrayList with all zeroes in Java? 我可以在ArrayList上使用类字段吗? <T> Java中的实例? - Can I use the class field on an ArrayList<T> instance in Java? 我可以在 ArrayList 中获取 object 的类型来实例化通用 class 吗? - Can I get the type of an object in an ArrayList to instantiate a generic class? 如何将泛型类型的类对象强制转换为该类型的特定实例 - How to Cast the Class Object of a Generic Type to a Specific Instance of that Type 如何使用 Stream Stream map 将 Object 类型的实例转换为 Java 中的特定 Class - How to map an instance of type Object to specific Class in Java using Stream API
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM