如何在java中的每个arraylist中创建具有不同类型对象的arraylist数组?

问题描述 投票:-1回答:3

我想创建一个ArrayList对象数组。

让我们假设数组大小为3,因此它包含3个列表。在ArrayList的每个索引处存储在ArrayList中的数据类型是不同的,例如:索引0处的ArrayList包含Class“student”的对象,索引1处的ArrayList包含Class“Professor”的对象,索引2处的ArrayList包含Class“的对象家长”。

如何创建它?

java arrays arraylist
3个回答
1
投票

实际上,在safelly中你可以考虑ArrayList的对象。详细创建像这样的类;

Person.class

public class Person{
    //common fields of person
}

Student.class

public class Student extends Person{
  //fields of Student
}

Professor.class

public class Professor extends Person{
  //fields of Professor
}

Parent.class

public class Parent extends Person{
  //fields of Parent
}

现在你可以从泛型类创建这样的ArrayList数组。这个实现是;

ArrayList<ArrayList<Person>> personList = new ArrayList<>();

//studentList is keeps instance of Person as student
ArrayList<Person> students = new ArrayList<>();
students.add(new Student());
personList.add(students);

//professorsList is keeps instance of Person as professor
ArrayList<Person> professors = new ArrayList<>();
students.add(new Professor());
personList.add(professors);

//parentList is keeps instance of Person as parents
ArrayList<Person> parents = new ArrayList<>();
students.add(new Parent());
personList.add(parents);

更多阅读:ArrayList


0
投票

你可以使用not parametrized ArrayList

List<List> genericList = new ArrayList<List>();
genericList.add(*new ArrayList()*);

但不建议这样做,因为您将丢失有关每个列表类型的信息。 (你必须自己施展)


0
投票

这看起来像这样:

import java.util.ArrayList; 
public class HelloWorld{

     public static void main(String []args){
         ArrayList<ArrayList> arrs = new ArrayList<ArrayList>();
         arrs.add(new ArrayList<String>());
         arrs.add(new ArrayList<Integer>());
         arrs.add(new ArrayList<Double>());
         ((ArrayList<String>)arrs.get(0)).add("Hello World!");
        System.out.println(arrs.get(0).get(0));
     }
}

这不是完全安全的,因为您必须使用您在父ArrayList的每次检索中期望的泛型类型来转换ArrayList。

© www.soinside.com 2019 - 2024. All rights reserved.