I am making an algorithm to save a path of zeroes between 0 1 array the length of the path will be variable and so i need an array without predefined length
-
1use Java collections, List for oneOleg Mikheev– Oleg Mikheev2012-03-05 13:16:41 +00:00Commented Mar 5, 2012 at 13:16
-
There's no way do initialize the array size dynamically. Why don't you use Collections?NIVESH SENGAR– NIVESH SENGAR2012-03-05 13:17:30 +00:00Commented Mar 5, 2012 at 13:17
-
Do you mean that, once the array is created, it cannot vary in size; or that each time the array is created, it must be of a different (i.e. variable) size?jyoungdev– jyoungdev2012-03-05 13:30:08 +00:00Commented Mar 5, 2012 at 13:30
10 Answers
Use ArrayList instead. An ordinary array cannot be resized so easily - you would have to create a new one of a bigger size and copy the old one into it - I would not recommend this.
Comments
You can always create array dynamically, e.g. new int[n] where n contains the array length at this moment (not pre-defined at compile time).
But array size cannot be changed. If you need this you should use List instead:
List<Integer> list = new ArrayList<Integer>();
Now you can add and remove elements when you need and the list size will be changed dynamically: you do not have to care about it:
list.add(123);
list.remove(456);
Comments
If speed is a real issue... and you need a dynamically changing array, you could try the following:
// this only works for increasing array-size
int[] tmp = new int[new_bigger_size]; // create a new array
System.arraycopy(array, 0, tmp, 0, array.length); // copy the data
int nextPosition = array.length
array = tmp; // assign the reference
// from position array.length (nextPosition), the new elements can be copied,
// for example:
array[nextPosition] = 120;
....
NOTE! This is very C-ish and not ideal. It is also more difficult to maintain uses more memory during the resizing and is regarded as bad form. Only try this as a last resort and if an ArrayList is really not working for you in terms of speed.
Having said that, does someone have an idea of how much slower (if any) an ArrayList will be?