-1

for my program I need to create an array of ArrayLists.

Is this even possible?

This is the code I am trying to use:

public static ArrayList<Chemical> [] [] chemicals;
chemicals = new ArrayList<Chemical>[cols][rows];

It gives a generic array creation error.

Thank you.

andrewn
  • 7
  • 1
  • 2
  • @pickypg Not really a duplicate - the issue there is trying to use a primitive with generics. – Bernhard Barker May 31 '14 at 02:34
  • @Dukeling Yeah, I noticed it was `int` rather than `Integer` after marking it, but the similarity still exists even though I prefer yours. – pickypg May 31 '14 at 02:37
  • You can use `List Within list` to overcome the problem of to defining row and column at coding time like List> listOfLists = new ArrayList>(); – user3145373 ツ May 31 '14 at 04:27

3 Answers3

3

This seems to work in Java 8

ArrayList<Chemical>[][] chemicals = new ArrayList[cols][rows];
Zeb Barnett
  • 168
  • 2
  • 11
0

Do this

public static ArrayList<Chemical> [] [] chemicals;
chemicals  = new ArrayList[cols][rows];

and put @SuppressWarnings("unchecked") on the class

Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
0

You can do it in following ways :

1.

List<List<Chemical>> listOfLists = new ArrayList<List<Chemical>>();

or other way :

2.

It may be more appropriate to use a Map<Chemical, List<Chemical>>. Having the value of the Map as a List<Chemical> will allow you to expand the list as opposed to an array which has a fixed size.

public static void main(String[] args) throws CloneNotSupportedException {
    Map<Chemical, List<Chemical>> myMap = create(1, 3);
}

public static Map<Chemical, List<Chemical>> create(double row, double column) {
    Map<Chemical, List<Chemical>> chemicalMap = new HashMap<Chemical, List<Chemical>>();

    for (double x = 0; x < row; x++) {
        for (double y = 0; y < column; y++) {
            chemicalMap.put(x, new ArrayList<Chemical>());
        }
    }
    return chemicalMap;
}
user3145373 ツ
  • 7,858
  • 6
  • 43
  • 62