Reputation: 87
I have a task, where I need to store data into arrays. But the problem which I met, that for using array I should initialize it. But I do not know how much items will be stored there. For example:
int[] array_name;
array_name = {1,2,3};
But my task is find numbers from string, and stored them into array, how much numbers will be there I do not know. Is there any universal way to initialize array?
Upvotes: 1
Views: 78
Reputation: 28747
In that case you use an ArrayList
.
ArrayList
uses internally an array which grows automatically.
If you insist on using an array, you can create one, once you have read in all data into your ArrayList
.
Example:
List<Integer> numbers= new ArrayList<Integer>();
numbers.add(1);
numbers.add(2);
...
Upvotes: 6
Reputation: 803
Arrays in Java are not dynamic. You can use list instead.
List<Integer> list = new ArrayList<Integer>();
Due to autoboxing feature you can freely add either Integer objects or primitive ints to this list.
Upvotes: 1
Reputation: 711
Create a List...
List myList = new ArrayList();
or with generics
List<MyType> myList = new ArrayList<MyType>();
If you definetly need an array, then after adding everything to the list, make it an array. More info here
Upvotes: 1
Reputation: 12523
I suggest you to use a List for that:
List<Integer> lIntegerList = new ArrayList<Integer>();
For using that there is no need to know how much Integers you have.
Upvotes: 1