226

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?

14
  • 10
    Don't mix arrays and collections. In fact, don't use arrays unless you are dealing with primitives (or you know what you are doing). Arrays are a usability nightmare, they make your code unmaintainable. Dec 19, 2011 at 9:14
  • 19
    @SeanPatrickFloyd Can you explain why arrays are usability nightmare?
    – user
    May 13, 2012 at 10:58
  • 3
    @crucifiedsoul sure. an array can't grow, you can't insert anything into an array, an array doesn't override standard methods like equals hashcode or toString etc. May 13, 2012 at 16:45
  • 10
    @SeanPatrickFloyd okay -- well I need exactly four arraylists -- I plan to access each one by index -- I don't need the outer array to grow or shrink -- I don't need any toString or hashcode, etc. -- to me, an array is the obvious choice here -- what would you recommended as an alternative in this situation? Mar 14, 2015 at 22:04
  • 5
    Okay this is an old question but I'm going to ask anyway and see if anyone answers. I'm seeing everyone talking about why an array of lists is a terrible idea, bad coding practice, etc. I looked this up because I'm learning to do hash chains, and the definition of a hash chain is an array of lists! So how exactly can a central programming data structure be terrible coding practice? Or does this just fall into the IYKWYD category mentioned by @Sean?
    – jimboweb
    Nov 5, 2016 at 13:04

20 Answers 20

164

As per Oracle Documentation:

"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:

List<List<Individual>> group = new ArrayList<List<Individual>>(4);
7
  • 5
    What does "cannot create an array of generic type" mean? That doesn't really make sense to me because its not a generic if you provide what its suppose to hold, right?
    – Andy
    Sep 1, 2012 at 21:57
  • 7
    I am surprised of the upvotes as It doesnt' answer the question (i.e. I want to do this, how can I do it). Except maybe for the 1st sentence.
    – Florian F
    Jun 30, 2015 at 13:59
  • 21
    why is List reference better than ArrayList?
    – shifu
    Jul 8, 2015 at 15:24
  • 4
    @shifu a List reference is more general than ArrayList; declaring as List abstracts away the API of ArrayList that extends beyond List API. That is good be cause it simplifies the reference to List whose API probably has the entirety of what the List is needed for anyways, without cluttering that reference's API with the extras ArrayList has. You should only declare as ArrayList if you need something specific from its API to be available via the reference.
    – cellepo
    Mar 22, 2016 at 21:22
  • 2
    Any reason this would be preferable over @kelvincer simpler Answer (ArrayList<String>[] group = new ArrayList[4])? Especially if vanilla array API was all that was needed anyways?
    – cellepo
    Mar 22, 2016 at 21:23
131

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 will need to suppress the warning but it's safe in this case.

6
  • 7
    No one seems to explain well why and i like your snippet above. why do you recommend using list over this?
    – clankill3r
    Jun 17, 2013 at 13:05
  • 7
    If array group doesn't change, then this approach is better, because arrays are faster than List<> classes.
    – Borzh
    Jun 17, 2015 at 18:45
  • 54
    Thanks for actually answering the question. There is no logical reason to automatically presume a list is preferable to an array without further context. Nov 19, 2015 at 13:23
  • 3
    You should use new ArrayList<?>[N] to avoid using a raw type.
    – Radiodef
    May 16, 2017 at 14:33
  • 2
    List<Integer>[] subsets=(List<Integer>[])new ArrayList[length] also does the work
    – ZhaoGang
    Oct 14, 2018 at 7:29
94

This works:

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

Though it will produce a warning that you may want to suppress.

2
  • 1
    This satisfyingly has the desired benefit that adding an ArrayList of any Object besides String (i.e: ArrayList<String> instead of ArrayList<NotString>) to group does not compile
    – cellepo
    Mar 22, 2016 at 21:37
  • @SuppressWarnings("unchecked")
    – baz
    Aug 8, 2022 at 14:59
32

You can create a class extending ArrayList

class IndividualList extends ArrayList<Individual> {

}

and then create the array

IndividualList[] group = new IndividualList[10];
29

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<>());
0
8

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.

6

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

2
  • Adding at a specific position is O(n) for both array and ArrayList. Filling is also O(n) for both arrays and ArrayList.
    – Navin
    Jan 1, 2014 at 13:17
  • 2
    Adding at a specific position is O(1) for arrays. It's O(n) for ArrayList, but O(1) for arrays.
    – aviemet
    Mar 21, 2014 at 6:19
3

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];
2
  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);
    
2

List[] listArr = new ArrayList[4];

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

0
1

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.

1
ArrayList<String>[] lists = (ArrayList<String>[])new ArrayList[10]; 
1
  • why did you casted new ArrayList[4] with (ArrayList<Individual>[])? I tried and it looks like it works fine without casting too. Apr 30, 2022 at 14:00
1

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.

1
  • why did you casted new ArrayList[4] with (ArrayList<Individual>[])? I tried and it looks like it works fine without casting too. Apr 30, 2022 at 14:01
1

ArrayList<Integer>[] graph = new ArrayList[numCourses] It works.

0
1

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--. I then assigned each of the Arraylists to an index of the array:

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

Hope that helps if anyone runs into a similar issue.

0

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

You can do thi. 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>();
}
0

If you want to avoid Java warnings, and still have an array of ArrayList, you can abstract the ArrayList into a class, like this:

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];
-1
ArrayList<String> al[] = new ArrayList[n+1];
for(int i = 0;i<n;i++){
   al[i] = new ArrayList<String>();
}
0
-3

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.

2
  • 2
    l.length is undefined in the for-loop. This might be a runtime error. Jan 22, 2015 at 20:49
  • l is not initialized to have a length, it is a still a null pointer when it reaches the for loop. i e List<e>[] l = new List[LENGTH];
    – Erik
    Oct 11, 2017 at 8:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.