2

I want to declare multiple arraylists but i failed to do so. Is there a way to it? here's my failed code:

List<Integer>[] table = new ArrayList<Integer>[]();

It seems no matter how and where do i put '[]', it just doesn't work. any help or suggestion would be appreciated

7
  • 3
    Always specify the error you're receiving at the same time as the code that doesn't work. I assume this is failing at compile time? What's the error? (Note that that syntax is broken to start with as you're not specifying the size of the array, and you've got () as if you were calling a constructor, which you're not.) Commented Nov 11, 2015 at 6:43
  • 1
    List<Integer> table = new ArrayList<Integer>() Commented Nov 11, 2015 at 6:44
  • 1
    @karimmohsen: No, that creates a single list. The OP wants multiple lists. Commented Nov 11, 2015 at 6:45
  • 2
    Basically, the answer is that arrays and generics don't mix well in Java. You should consider using a List<List<Integer>> instead. Commented Nov 11, 2015 at 6:46
  • 2
    @karimmohsen: No need for it to be declared as an ArrayList<ArrayList<Integer>> - I'd just go with List<List<Integer>>, personally. Then you can add ArrayList<Integer> references to it - or other implementations. Commented Nov 11, 2015 at 6:52

3 Answers 3

2

You have to specify the size like this:

ArrayList<Integer>[] table = new ArrayList[10];

Creates an array of ArrayList with capacity of 10.

Sign up to request clarification or add additional context in comments.

2 Comments

it looks good, but i received 'uses unchecked or unsafe operations.' when compiling.
This is it, your array can't be sure that Lists that it holds will include just Integers. Yes this is unsafe, and actually using of arrays is unsafe and it's considered bad practice.
1
@SuppressWarnings("unchecked")
List<Integer>[] table = (ArrayList<Integer>[]) Array.newInstance(ArrayList.class, size);

Comments

0
List<Integer> multiple = new ArrayList<String>(), myArray = new ArrayList<String>();

hope it helps.

1 Comment

It seems clear that the poster is trying to allocate an array of ArrayLists (despite the misleading title). This doesn't help with that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.