How can I create an Array of ArrayLists?
Asked Answered
S

21

227

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?

Singhalese answered 19/12, 2011 at 9:9 Comment(14)
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.Uta
@SeanPatrickFloyd so you should avoid arraylists and arrays? (talking about java types). Are lists the alternative?Juror
@Keyser an arraylist is a list that's backed by an array. Lists are fine, including arraylists.Uta
@SeanPatrickFloyd Can you explain why arrays are usability nightmare?Singhalese
@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.Uta
@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?Roseannaroseanne
@Roseannaroseanne 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 ArraysUta
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?Aestheticism
@Aestheticism and why can't you use a list of lists instead?Uta
@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.Aestheticism
@Aestheticism 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)Uta
@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.Aestheticism
@Aestheticism 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 internallyUta
@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.Aestheticism
H
167

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);
Hoarding answered 19/12, 2011 at 9:9 Comment(7)
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?Tantalus
@Tantalus 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.Extra
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.Pappas
why is List reference better than ArrayList?Mail
@Mail 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.Heavenward
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?Heavenward
In Java 9 and later List<List<Type>> group = new ArrayList<>();Thibodeau
T
133

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.

Tyson answered 19/12, 2011 at 9:21 Comment(6)
No one seems to explain well why and i like your snippet above. why do you recommend using list over this?Miniaturist
If array group doesn't change, then this approach is better, because arrays are faster than List<> classes.Hessian
Thanks for actually answering the question. There is no logical reason to automatically presume a list is preferable to an array without further context.Loch
You should use new ArrayList<?>[N] to avoid using a raw type.Cleveite
List<Integer>[] subsets=(List<Integer>[])new ArrayList[length] also does the workAstraea
why do we need to cast new ArrayList[4] with (ArrayList<Individual>[])? I tried and it looks like it works fine without casting too.Unreconstructed
T
95

This works:

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

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

Teetotum answered 18/2, 2015 at 16:5 Comment(2)
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 compileHeavenward
@SuppressWarnings("unchecked")Harbourage
C
34

You can create a class extending ArrayList

class IndividualList extends ArrayList<Individual> {

}

and then create the array

IndividualList[] group = new IndividualList[10];
Conlee answered 7/7, 2013 at 14:22 Comment(0)
I
30

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<>());
Incredible answered 27/4, 2016 at 13:3 Comment(0)
S
9

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.

Sarmentum answered 22/5, 2015 at 8:49 Comment(0)
V
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

Vaticinate answered 22/6, 2013 at 3:9 Comment(2)
Adding at a specific position is O(n) for both array and ArrayList. Filling is also O(n) for both arrays and ArrayList.Crossbench
Adding at a specific position is O(1) for arrays. It's O(n) for ArrayList, but O(1) for arrays.Exobiology
C
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];
Calves answered 19/12, 2011 at 9:13 Comment(0)
I
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);
    
Immobilize answered 26/3, 2014 at 10:39 Comment(0)
D
2

List[] listArr = new ArrayList[4];

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

Dictatorship answered 27/1, 2018 at 14:18 Comment(0)
M
1
ArrayList<String>[] lists = (ArrayList<String>[])new ArrayList[10]; 
Mulloy answered 30/10, 2015 at 9:35 Comment(1)
why did you casted new ArrayList[4] with (ArrayList<Individual>[])? I tried and it looks like it works fine without casting too.Unreconstructed
O
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.

Opia answered 17/12, 2015 at 18:54 Comment(0)
A
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.

Amaral answered 14/11, 2017 at 5:53 Comment(1)
why did you casted new ArrayList[4] with (ArrayList<Individual>[])? I tried and it looks like it works fine without casting too.Unreconstructed
S
1

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

Spirochaetosis answered 10/9, 2018 at 4:41 Comment(0)
L
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.

Litt answered 23/4, 2021 at 12:19 Comment(0)
R
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>();
 }
Rural answered 13/6, 2015 at 3:11 Comment(0)
P
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>();
}
Ptisan answered 20/10, 2016 at 11:12 Comment(0)
I
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];
Ithunn answered 6/8, 2021 at 0:16 Comment(0)
P
0

The syntax you're looking for is as follows:

ArrayList[] group = new ArrayList[4];

It's not at all complicated, as long as you are careful not to add objects of other types to group.

Periderm answered 26/3, 2024 at 11:26 Comment(0)
P
-1
ArrayList<String> al[] = new ArrayList[n+1];
for(int i = 0;i<n;i++){
   al[i] = new ArrayList<String>();
}
Proven answered 20/2, 2018 at 4:44 Comment(0)
A
-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.

Arte answered 20/5, 2014 at 6:19 Comment(2)
l.length is undefined in the for-loop. This might be a runtime error.Radiate
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];Migraine

© 2022 - 2025 — McMap. All rights reserved.