-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.

3
  • @pickypg Not really a duplicate - the issue there is trying to use a primitive with generics. Commented May 31, 2014 at 2:34
  • @Dukeling Yeah, I noticed it was int rather than Integer after marking it, but the similarity still exists even though I prefer yours. Commented May 31, 2014 at 2:37
  • You can use List Within list to overcome the problem of to defining row and column at coding time like List<List<Chemical>> listOfLists = new ArrayList<List<Chemical>>(); Commented May 31, 2014 at 4:27

3 Answers 3

3

This seems to work in Java 8

ArrayList<Chemical>[][] chemicals = new ArrayList[cols][rows];
Sign up to request clarification or add additional context in comments.

1 Comment

It works in Java 7 and Java 6 too
0

Do this

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

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

Comments

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;
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.