224

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?

Michael
  • 41,989
  • 11
  • 82
  • 128
user
  • 5,335
  • 7
  • 47
  • 63
  • 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. – Sean Patrick Floyd Dec 19 '11 at 09:14
  • @SeanPatrickFloyd so you should avoid arraylists and arrays? (talking about java types). Are lists the alternative? – keyser May 13 '12 at 08:44
  • 2
    @Keyser an arraylist is a list that's backed by an array. Lists are fine, including arraylists. – Sean Patrick Floyd May 13 '12 at 10:45
  • 19
    @SeanPatrickFloyd Can you explain why arrays are usability nightmare? – user May 13 '12 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. – Sean Patrick Floyd May 13 '12 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? – BrainSlugs83 Mar 14 '15 at 22:04
  • 2
    @BrainSlugs83 well then that might fall into the "or you know what you are doing" category. I'm not saying arrays should never be used, but in 99% of use cases, collections are the better fit. Also read Effective Java Item 25: Prefer Lists to Arrays – Sean Patrick Floyd Mar 15 '15 at 11:06
  • 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 05 '16 at 13:04
  • @jimboweb and why can't you use a list of lists instead? – Sean Patrick Floyd Nov 06 '16 at 06:03
  • 1
    @SeanPatrickFloyd because of the way that lists items are retrieved as opposed to arrays. An array has a direct address, meaning that items[7] is at the memory location items[0] + 7*the memory size of item. It's an O(1) operation, then you search the relatively small list in that array. A list is a series of links from one item to the next. If it's a list and I say items.get(7) it has to go through all 7 items to get to the 7th item - not a big deal if it's only 7, but if it's item.get(10000) then it is. It's an O(n) operation, which is much, much slower if you're working with huge data sets. – jimboweb Nov 06 '16 at 22:05
  • @jimboweb that's true for Linked Lists, but an ArrayList is best of both worlds: it has the efficiency of arrays and the usability of lists (there's a tiny overhead for the list container, but not much) – Sean Patrick Floyd Nov 06 '16 at 22:07
  • @SeanPatrickFloyd I didn't make all this up. This is a basic data structure you'll see in any beginning Data Structures and Algorithms textbook. – jimboweb Nov 06 '16 at 22:07
  • 2
    @jimboweb I'm not saying you did. I'm saying that in CS terms, an ArrayList is more like an array than like a list. List is just an interface, with different implementations. This one uses arrays internally – Sean Patrick Floyd Nov 06 '16 at 22:09
  • @SeanPatrickFloyd okay, that may be true. I didn't realize that about the ArrayList. I guess because it's called a list I assumed it was more like a list. I will look it up. – jimboweb Nov 06 '16 at 22:19

20 Answers20

163

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);
YoYo
  • 9,157
  • 8
  • 57
  • 74
MByD
  • 135,866
  • 28
  • 264
  • 277
  • 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 01 '12 at 21:57
  • @Andy I think he's saying "it's a limitation of Java that you cannot create an array of Generic objects", appears that way to me. – Ben Clayton Mar 04 '14 at 13:12
  • 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 '15 at 13:59
  • 20
    why is List reference better than ArrayList? – shifu Jul 08 '15 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 '16 at 21:22
  • 2
    Any reason this would be preferable over @kelvincer simpler Answer (`ArrayList[] group = new ArrayList[4]`)? Especially if vanilla array API was all that was needed anyways? – cellepo Mar 22 '16 at 21:23
  • 1
    In Java 9 and later `List> group = new ArrayList<>();` – Gayan Weerakutti Nov 01 '18 at 16:44
129

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.

Michael
  • 41,989
  • 11
  • 82
  • 128
Marcus
  • 12,296
  • 5
  • 48
  • 66
  • 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 '13 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 '15 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. – Special Sauce Nov 19 '15 at 13:23
  • 3
    You should use `new ArrayList>[N]` to avoid using a raw type. – Radiodef May 16 '17 at 14:33
  • 2
    `List[] subsets=(List[])new ArrayList[length]` also does the work – ZhaoGang Oct 14 '18 at 07:29
  • 1
    why do we need to cast `new ArrayList[4]` with `(ArrayList[])`? I tried and it looks like it works fine without casting too. – Yogesh_Singh Apr 30 '22 at 13:51
93

This works:

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

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

Michael
  • 41,989
  • 11
  • 82
  • 128
kelvincer
  • 5,929
  • 6
  • 27
  • 32
  • 1
    This satisfyingly has the desired benefit that adding an ArrayList of any Object besides String (i.e: `ArrayList` instead of `ArrayList`) to `group` does not compile – cellepo Mar 22 '16 at 21:37
  • ``@SuppressWarnings("unchecked")`` – baz Aug 08 '22 at 14:59
31

You can create a class extending ArrayList

class IndividualList extends ArrayList<Individual> {

}

and then create the array

IndividualList[] group = new IndividualList[10];
user2558221
  • 311
  • 3
  • 2
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<>());
Michael
  • 41,989
  • 11
  • 82
  • 128
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.

Rich
  • 3,928
  • 4
  • 37
  • 66
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

Mark Odey
  • 170
  • 2
  • 12
  • 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 01 '14 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 '14 at 06: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];
Piotr Gwiazda
  • 12,080
  • 13
  • 60
  • 91
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);
    
Amr Lotfy
  • 2,937
  • 5
  • 36
  • 56
2

List[] listArr = new ArrayList[4];

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

Ashutosh Shukla
  • 557
  • 5
  • 9
1
ArrayList<String>[] lists = (ArrayList<String>[])new ArrayList[10]; 
Pang
  • 9,564
  • 146
  • 81
  • 122
Labeo
  • 5,831
  • 13
  • 47
  • 77
  • why did you casted `new ArrayList[4]` with `(ArrayList[])`? I tried and it looks like it works fine without casting too. – Yogesh_Singh Apr 30 '22 at 14:00
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.

Radiodef
  • 37,180
  • 14
  • 90
  • 125
Androidcoder
  • 4,389
  • 5
  • 35
  • 50
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.

Tejendra
  • 159
  • 9
  • why did you casted `new ArrayList[4]` with `(ArrayList[])`? I tried and it looks like it works fine without casting too. – Yogesh_Singh Apr 30 '22 at 14:01
1

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

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.

Freud
  • 11
  • 1
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>();
 }
Creative_Cimmons
  • 255
  • 1
  • 2
  • 11
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>();
}
Michael
  • 41,989
  • 11
  • 82
  • 128
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];
Craigo
  • 3,384
  • 30
  • 22
-1
ArrayList<String> al[] = new ArrayList[n+1];
for(int i = 0;i<n;i++){
   al[i] = new ArrayList<String>();
}
HeadAndTail
  • 804
  • 8
  • 9
-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.