简体   繁体   English

如何在Java中声明匿名arraylist?

[英]How to declare anonymous arraylist in java?

I want to declare anonymous arraylist in java so that on the nature of constructor list can be initialize with any type of object. 我想在Java中声明匿名arraylist,以便可以使用任何类型的对象初始化构造函数列表的性质。 For example: 例如:

    ArrayList<Anonymous> list;

    public AdapterChatWindow(Activity act, ArrayList<CommentData> list, String extras) {        
        this.act = act;     
        this.list = list;
    }

    public AdapterChatWindow(Activity act, ArrayList<ChatHistory> list) {       
        this.act = act; 
        this.list = list;
    }

Is this possible? 这可能吗? Any alternate Solution? 还有其他解决方案吗? Is this possible with list type data structure? 列表类型数据结构可能吗?

You can use a generic type: 您可以使用通用类型:

public class AdapterChatWindow<T>
{
    ArrayList<T> list;

    public AdapterChatWindow(Activity act, ArrayList<T> list, String extras)
// ....

Then use it like this: 然后像这样使用它:

AdapterChatWindow<Foo> acw = new AdapterChatWindow<Foo>(...);

You can go for generic for example.. 例如,您可以选择通用。

{List<? extends "your super class"> list;}

now you can initialize your list with any of the subclass of "your super class" 现在,您可以使用“您的超类”的任何子类来初始化列表

您可以只使用ArrayList<Object> list但是当您想对它们进行任何操作时,都必须仔细转换它们。

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

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