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

0

4 Answers 4

1

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

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

2 Comments

No, its size is 0. Its capacity is 10.
yes, my bad. capacity is 10 and size is 0. thanks
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.

Comments

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

Comments

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<>());

4 Comments

No, its size is 0. Its capacity is 128.
@AndyTurner Ah, yes. I got it mixed up with the behavior of vectors from C++. What do you think of my edit?
I simply wouldn't have mentioned capacity, especially as you don't say why it is probably irrelevant.
Thank you very much! Your method works!! @Nulano

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.