简体   繁体   English

如何创建一个 ArrayLists 数组?

[英]How can I create an Array of ArrayLists?

I am wanting to create an array of arraylist like below:我想创建一个数组,如下所示:

ArrayList<Individual>[] group = new ArrayList<Individual>()[4];

But it's not compiling.但它没有编译。 How can I do this?我怎样才能做到这一点?

As per Oracle Documentation :根据Oracle 文档

"You cannot create arrays of parameterized types" “您不能创建参数化类型的数组”

Instead, you could do:相反,你可以这样做:

ArrayList<ArrayList<Individual>> group = new ArrayList<ArrayList<Individual>>(4);

As suggested by Tom Hawting - tackline, it is even better to do:正如 Tom Hawting 所建议的 - 主攻,最好这样做:

List<List<Individual>> group = new ArrayList<List<Individual>>(4);

As the others have mentioned it's probably better to use another List to store the ArrayList in but if you have to use an array:正如其他人所提到的,使用另一个 List 来存储 ArrayList 可能更好,但如果您必须使用数组:

ArrayList<Individual>[] group = (ArrayList<Individual>[]) new ArrayList[4];

You will need to suppress the warning but it's safe in this case.您将需要取消警告,但在这种情况下是安全的。

This works:这有效:

ArrayList<String>[] group = new ArrayList[4];

Though it will produce a warning that you may want to suppress.虽然它会产生一个你可能想要抑制的警告。

You can create a class extending ArrayList您可以创建一个扩展 ArrayList 的类

class IndividualList extends ArrayList<Individual> {

}

and then create the array然后创建数组

IndividualList[] group = new IndividualList[10];

You can create Array of ArrayList您可以创建 ArrayList 的数组

List<Integer>[] outer = new List[number];
for (int i = 0; i < number; i++) {
    outer[i] = new ArrayList<>();
}

This will be helpful in scenarios like this.这在这样的场景中会很有帮助。 You know the size of the outer one.你知道外面的大小。 But the size of inner ones varies.但内部的大小各不相同。 Here you can create an array of fixed length which contains size-varying Array lists.在这里,您可以创建一个固定长度的数组,其中包含大小可变的数组列表。 Hope this will be helpful for you.希望这对你有帮助。

In Java 8 and above you can do it in a much better way.Java 8及更高版本中,您可以以更好的方式做到这一点。

List<Integer>[] outer = new List[number];
Arrays.setAll(outer, element -> new ArrayList<>());

I am wanting to create an array of arraylist like below:我想要创建一个arraylist数组,如下所示:

ArrayList<Individual>[] group = new ArrayList<Individual>()[4]

But it's not compiling.但是它没有编译。 How can I do this?我怎样才能做到这一点?

This works, array of ArrayList.这有效,ArrayList 数组。 Give it a try to understand how it works.尝试了解它是如何工作的。

import java.util.*;

public class ArrayOfArrayList {
    public static void main(String[] args) {

        // Put the length of the array you need
        ArrayList<String>[] group = new ArrayList[15];
        for (int x = 0; x < group.length; x++) {
            group[x] = new ArrayList<>();
        }

        //Add some thing to first array
        group[0].add("Some");
        group[0].add("Code");

        //Add some thing to Secondarray
        group[1].add("In here");

        //Try to output 'em
        System.out.println(group[0]);
        System.out.println(group[1]);
    }
}

Credits to Kelvincer for some of codes.部分代码归功于 Kelvincer。

The problem with this situation is by using a arraylist you get a time complexity of o(n) for adding at a specific position.这种情况的问题是通过使用数组列表,您在特定位置添加的时间复杂度为 o(n)。 If you use an array you create a memory location by declaring your array therefore it is constant如果使用数组,则通过声明数组来创建内存位置,因此它是常量

  1. Creation and initialization创建和初始化

    Object[] yourArray = new Object[ARRAY_LENGTH];
  2. Write access写权限

    yourArray[i]= someArrayList;

    to access elements of internal ArrayList:访问内部 ArrayList 的元素:

     ((ArrayList<YourType>) yourArray[i]).add(elementOfYourType); //or other method
  3. Read access读取权限

    to read array element i as an ArrayList use type casting:读取数组元素 i 作为 ArrayList 使用类型转换:

     someElement= (ArrayList<YourType>) yourArray[i];

    for array element i: to read ArrayList element at index j对于数组元素 i:读取索引 j 处的 ArrayList 元素

    arrayListElement= ((ArrayList<YourType>) yourArray[i]).get(j);

List[] listArr = new ArrayList[4]; List[] listArr = new ArrayList[4];

Above line gives warning , but it works (ie it creates Array of ArrayList)上面的行给出了警告,但它有效(即它创建了 ArrayList 的数组)

You can't create array of generic type.您不能创建泛型类型的数组。 Create List of ArrayLists :创建 ArrayLists 列表:

 List<ArrayList<Individual>> group = new ArrayList<ArrayList<Individual>>();

or if you REALLY need array (WARNING: bad design!):或者如果你真的需要数组(警告:糟糕的设计!):

 ArrayList[] group = new ArrayList[4];
ArrayList<String>[] lists = (ArrayList<String>[])new ArrayList[10]; 

To declare an array of ArrayLists statically for, say, sprite positions as Points:静态声明一个 ArrayList 数组,例如,精灵位置为点:

ArrayList<Point>[] positionList = new ArrayList[2];

public Main(---) {
    positionList[0] = new ArrayList<Point>(); // Important, or you will get a NullPointerException at runtime
    positionList[1] = new ArrayList<Point>();
}

dynamically:动态:

ArrayList<Point>[] positionList;
int numberOfLists;

public Main(---) {
    numberOfLists = 2;
    positionList = new ArrayList[numberOfLists];
    for(int i = 0; i < numberOfLists; i++) {
        positionList[i] = new ArrayList<Point>();
    }
}

Despite the cautions and some complex suggestions here, I have found an array of ArrayLists to be an elegant solution to represent related ArrayLists of the same type.尽管这里有警告和一些复杂的建议,但我发现 ArrayLists 数组是表示相同类型的相关 ArrayLists 的优雅解决方案。

You can create like this ArrayList<Individual>[] group = (ArrayList<Individual>[])new ArrayList[4];你可以像这样创建ArrayList<Individual>[] group = (ArrayList<Individual>[])new ArrayList[4];

You have to create array of non generic type and then cast it into generic one.您必须创建非泛型类型的数组,然后将其转换为泛型类型。

ArrayList<Integer>[] graph = new ArrayList[numCourses]它有效。

I think I'm quite late but I ran into the same problem and had to create an array of arraylists as requested by my project in order to store objects of different subclasses in the same place and here is what I ended up doing:我想我已经很晚了,但我遇到了同样的问题,必须按照我的项目的要求创建一个数组列表,以便将不同子类的对象存储在同一个地方,这是我最终做的:

ArrayList<?>[] items = new ArrayList[4];
ArrayList<Chocolate> choc = new ArrayList<>();
ArrayList<Chips> chips = new ArrayList<>();
ArrayList<Water> water = new ArrayList<>();
ArrayList<SoftDrink> sd = new ArrayList<>();

since each arraylist in the array would contain different objects (Chocolate , Chips , Water and SoftDrink ) --it is a project to simulate a vending machine--.因为数组中的每个数组列表将包含不同的对象(Chocolate、Chips、Water 和 SoftDrink)——这是一个模拟自动售货机的项目——。 I then assigned each of the Arraylists to an index of the array:然后我将每个 Arraylists 分配给数组的索引:

items[0]=choc;
items[1]=chips;
items[2]=water;
items[3]=sd;

Hope that helps if anyone runs into a similar issue.如果有人遇到类似问题,希望能有所帮助。

I find this easier to use...我发现这更易于使用...

static ArrayList<Individual> group[];
......
void initializeGroup(int size)
{
 group=new ArrayList[size];
 for(int i=0;i<size;i++)
 {
  group[i]=new ArrayList<Individual>();
 }

You can do thi.你可以这样做。 Create an Array of type ArrayList创建一个 ArrayList 类型的数组

ArrayList<Integer>[] a = new ArrayList[n];

For each element in array make an ArrayList为数组中的每个元素创建一个 ArrayList

for(int i = 0; i < n; i++){ 
    a[i] = new ArrayList<Integer>();
}

If you want to avoid Java warnings, and still have an array of ArrayList, you can abstract the ArrayList into a class, like this:如果你想避免 Java 警告,并且仍然有一个 ArrayList 的数组,你可以将 ArrayList 抽象成一个类,如下所示:

public class Individuals {
    private ArrayList<Individual> individuals;
    
    public Individuals() {
        this.individuals = new ArrayList<>();
    }
    
    public ArrayList<Individual> getIndividuals() {
        return individuals;
    }
}

Then you can safely have:然后你可以安全地拥有:

Individuals[] group = new Individuals[4];
ArrayList<String> al[] = new ArrayList[n+1];
for(int i = 0;i<n;i++){
   al[i] = new ArrayList<String>();
}

you can create a List[] and initialize them by for loop.您可以创建一个 List[] 并通过 for 循环初始化它们。 it compiles without errors:它编译没有错误:

List<e>[] l;
for(int i = 0; i < l.length; i++){
    l[i] = new ArrayList<e>();
}

it works with arrayList[] l as well.它也适用于 arrayList[] l。

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

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