Array of ArrayList generic using accolades

Viewed 67

I want to have a predefined/fixed-size array of ArrayList but IntelliJ IDEA warns for an error.

This works:

String[] allPropsA = {prop.getProperty("xxx",""),prop.getProperty("yyy","")};
String[] allPropsB = new String[]{prop.getProperty("xxx",""),prop.getProperty("yyy","")}

public static ArrayList<String> a = new ArrayList<>();
public static ArrayList<String> b = new ArrayList<>();

ArrayList<ArrayList<String>> allListsA = new ArrayList<ArrayList<String>>();
allLists.add(a);
allLists.add(b);

But this does not work: ArrayList<String>[] allListsB = {a,b};

It gives me an error "java: generic array creation". Why is a nested ArrayList possible, but an oldschool array not? And how can I use the accolades/fixed-size style?

2 Answers

You can't create arrays of parameterized types, so you can't create an array or array lists. There are a couple things you can do. You can set the initial capacity of the array list by doing:

new ArrayList<ArrayList<String>>(capacity).

This ensures the ArrayList won't allocate another array buffer.

Or you can create a class for holding the array list object like so:

class ArrayListStringObject {
    ArrayList<String> data;
    public ArrayListStringObject(ArrayList<String> data) {
        this.data = data;
    }
}
ArrayListStringObject[] allListsB = {
    new ArrayListStringObject(a),
    new ArrayListStringObject(b),
    new ArrayListStringObject(c),
    ...
};

You can create factory method to create array of ArrayList<String>. For example:

@SuppressWarnings("unchecked")
public static ArrayList<String>[] newArray(int size){
    return new ArrayList[size]; //  Unchecked assignment
}

Unchecked assignment: 'java.util.ArrayList[]' to 'java.util.ArrayList<java.lang.String>[]' is isolated inside of the method body:

ArrayList<String> a = new ArrayList<>();
ArrayList<Integer> b = new ArrayList<>();        
ArrayList<String>[] allLists = newArray(2);
allLists[0] = a;
allLists[1] = b; //  error: incompatible types: ArrayList<Integer> cannot be converted to List<String>
Related