-4

I wrote a piece of code like this

ArrayList<Integer>[]list=new ArrayList<Integer>[128];

But Eclipse says

Cannot create a generic array of ArrayList

I also tried code like this

ArrayList<Integer>[]list=(ArrayList<Integer>[])new Object[128];

But Eclipse throws exception:

[Ljava.lang.Object; cannot be cast to [Ljava.util.ArrayList;

So how can I build an array of ArrayList< Integer > ?

Thanks a lot!!

Julian20151006
  • 191
  • 6
  • 12

4 Answers4

1

List<Integer> inp = new ArrayList<Integer>(10) to create list of integers whose size is 10.

Pramod V
  • 84
  • 3
0

Use this to create an ArrayList (remember, ArrayLists always have a theoretically indefinite capacity, since you can always add more elements to them - see a tutorial):

ArrayList<Integer> list = new ArrayList<>();

or this to make an array of ArrayLists:

ArrayList<Integer>[] lists = new ArrayList[128];

You will of course have to initialize your ArrayLists:

for (int i = 0; i < lists.length; i++)
    lists[i] = new ArrayList<>();

Alternatively, you can create an ArrayList of ArrayLists:

ArrayList<ArrayList<Integer>> lists2 = new ArrayList<>();
for (int i = 0; i < 128; i++)
     lists2.add(new ArrayList<>());
Nulano
  • 1,148
  • 13
  • 27
0

From what I see you are trying to create an ArrayList and an Array in the same step, which is impossible.

An Arraylist differs from arrays as it is a generic class, which means it has a lot more functionality.

For example:

In your code you are trying to specify a limit to the ArrayList, ArrayLists don't have a limit, they are expandable.

You can use the .add() function to add objects to ArrayLists, and get values using the .get(int index) function.

Example code:

ArrayList<Integer> myArray = new ArrayList<Integer>(); //initialized a new arrayList
myArray.add(7); //added element 7 at index 0
myArray.add(12); // added element 12 at index 1
print(myArray.get(1)) //output 12

You can check the documentations for the ArrayList class here.

Hope that helped.

Android Admirer
  • 2,310
  • 2
  • 17
  • 38
0

Your question isn't really clear, but to build an array list,this code should be sufficient

   ArrayList<Integer> list;
   list = new ArrayList<Integer>(128);
Kennedy
  • 547
  • 4
  • 23