[java] 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?

This question is related to java arrays arraylist

The answer is


This works:

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

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

  1. Creation and initialization

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

    yourArray[i]= someArrayList;
    

    to access elements of internal ArrayList:

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

    to read array element i as an ArrayList use type casting:

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

    for array element i: to read ArrayList element at index j

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

I totally do not get it, why everyone is suggesting the genric type over the array particularly for this question.

What if my need is to index n different arraylists.

With declaring List<List<Integer>> I need to create n ArrayList<Integer> objects manually or put a for loop to create n lists or some other way, in any way it will always be my duty to create n lists.

Isn't it great if we declare it through casting as List<Integer>[] = (List<Integer>[]) new List<?>[somenumber]. I see it as a good design where one do not have to create all the indexing object (arraylists) by himself

Can anyone enlighten me why this (arrayform) will be a bad design and what are its disadvantages?


The problem with this situation is by using a arraylist you get a time complexity of o(n) for adding at a specific position. If you use an array you create a memory location by declaring your array therefore it is constant


You can create like this ArrayList<Individual>[] group = (ArrayList<Individual>[])new ArrayList[4];

You have to create array of non generic type and then cast it into generic one.


To declare an array of ArrayLists statically for, say, sprite positions as Points:

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.


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:

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

You can't create array of generic type. Create List of 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> al[] = new ArrayList[n+1];
for(int i = 0;i<n;i++){
   al[i] = new ArrayList<String>();
}

This works, array of 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.


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>();
 }

List[] listArr = new ArrayList[4];

Above line gives warning , but it works (i.e it creates Array of ArrayList)


you can create a List[] and initialize them by for loop. 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<Integer>[] graph = new ArrayList[numCourses] It works.


You can do this :

//Create an Array of type ArrayList

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

//For each element in array make an ArrayList

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

You can create Array of 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.

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

Even better using method reference

List<Integer>[] outer = new List[10];
Arrays.setAll(outer,  ArrayList :: new);

You can create a class extending ArrayList

class IndividualList extends ArrayList<Individual> {

}

and then create the array

IndividualList[] group = new IndividualList[10];

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to arraylist

Adding null values to arraylist How to iterate through an ArrayList of Objects of ArrayList of Objects? Dynamically adding elements to ArrayList in Groovy How to replace existing value of ArrayList element in Java How to remove the last element added into the List? How to append elements at the end of ArrayList in Java? Removing Duplicate Values from ArrayList How to declare an ArrayList with values? In Java, can you modify a List while iterating through it? Load arrayList data into JTable