Java (Android) :具有多个类型的列表(字符串;整数;整数)

Java (Android) : List with multiples types (String; Integer; Integer)

如标题所示,我想要一个可以存储多种类型的列表。类似于:

List <String, Integer, Integer> myList;

myList.add("something", 1337, 123);

感谢您的帮助。

 class myClass   
   {
      public String myString;
      public Int numb1;
      public Int numb2;
   } 

...

List<myClass> TheList = new List<myClass>;

您可以定义一个结构或 class 来保存您的信息,然后创建一个列表

除了 List<Object>,您不能将多个不相关的类型添加到 Collection<?>。另外,myList.add("something", 1337, 123); 不是有效语法。

我想您正在加载一些 Android 适配器,因此我建议您创建一个 class,您可以将数据包装在其中。

public class StringIntInt {
    String s;
    int i1, i2;

    public StringIntInt(String s, int i1, int i2) {
        this.s = s;
        this.i1 = i1;
        this.i2 = i2;
    }
}

用例:

List<StringIntInt> myList = new ArrayList<StringIntInt>();
myList.add(new StringIntInt("something", 123, 1337);

I would like a list where I can store multiples types

最简单的方法是这样的:

List <Object> list = new ArrayList<Object>();
        list.add("Stringa");
        list.add(5);

问题是如果你需要操作它们,你应该非常注意:

        if(list.get(0) instanceof String){
            System.out.println(list.get(0));
        }
        else if(list.get(0) instanceof Integer){
            list.set(0, (Integer)list.get(0)+10);
        }

但在这里阅读:

List <String, Integer, Integer> myList;

也许您需要一些 class 作为元组使用:

public class Trio{
    String string;
    int value1;
    int value2;

    public Trio(String string, int value1, int value2) {
        this.string = string;
        this.value1 = value1;
        this.value2 = value2;
    }
}

然后使用这个:

List<Trio> list = new ArrayList<Trio>();
list.add(new Trio("String", 1, 2);