Jimmy lemieux
Jimmy lemieux

Reputation: 439

Populate an array with unlimited index - Java

Is there a way to populate an array with unlimited indexes in java? I just want the program to keep appending to the array without any capacity.

I declared like this:

int arrInt[] = new int[]

But it says that it is missing dimension. So how can I do it?

Upvotes: 0

Views: 1268

Answers (4)

MrPublic
MrPublic

Reputation: 518

In java, arrays have a maximum number of elements equal to Integer.MAX_VALUE - 5. To get around this, try using a LinkedList which has an unimited number of elements. Since this is a list, you can modify the size whenever necessary in your code. Note that ArrayList also has a max number of elements of Integer.MAX_VALUE, so LinkedList is necessary if you truly need a list of unlimited size.

Resource: http://docs.oracle.com/javase/7/docs/api/java/util/LinkedList.html

Upvotes: 1

Ankur Singhal
Ankur Singhal

Reputation: 26077

Is there a way to populate an array with unlimited indexes in java?

NO

I just want the program to keep appending to the array without any capacity.

Need to Use ArrayList

List<Object> arr = new ArrayList<Object>();
arr.add(obj1);
arr.add(obj2);
arr.add(obj3); .. so on

I declared like this - int arrInt[] = new int[]. But it says that it is missing dimension.

Arrays will always complain to declare the size.

Upvotes: 1

darthvading
darthvading

Reputation: 949

Array in Java is static, ie. you have to declare its size while initializing. Hence the answer is 'no' and you are getting the correct message as you have not mentioned the dimension.

Upvotes: 3

Eran
Eran

Reputation: 393836

No, there isn't.

ArrayList serves that purpose (i.e. an array based list whose capacity increases over time automatically when adding elements to it).

Upvotes: 1

Related Questions