Re: int[] array
O.L. wrote On 07/17/07 10:43,:
Hello,
I have a little problem with integer arrays ...
I need int[] arrays in some functions.
But when I create these int[], I don't know the int[] size at the
beginning because I add data in a loop. I tried to use ArrayList :
ArrayList<Integer> arr = new ArrayList<Integer>();
while(...) {
int n = ...;
arr.add(n);
}
But at the end I can't get the result in a int[] array ! I only get
Object[] array that I can't convert to int[].
The list holds Integer objects, not int values. You
could get an Integer[] from the list (there's more than
one method named toArray), but there's no way to "convert"
that array of object references to an array of int values.
You will need to extract the values, one by one.
Do you know what's the best way to use int[] buffers ?
What's the best way to define "best?"
One possibility is to proceed as you've begun, and
to follow the loop with
int[] array = new int[ arr.size() ];
for (int i = 0; i < array.length; ++i)
array[i] = arr.get(i).intValue();
Another is to guess at a likely array size and start
filling it, replacing it with larger arrays if needed and
perhaps with a truncated array at the end:
int[] array = new int[42];
int count = 0;
while (...) {
int n = ...;
if (count == array.length) {
int[] temp = new int[ count * 2 ];
System.arrayCopy(array, 0, temp, 0, count);
array = temp;
}
array[count++] = n;
}
// optional:
if (count < array.length) {
int[] temp = new int[count];
System.arrayCopy(array, 0, temp, 0, count);
array = temp;
}
Still another is to ponder how badly you need an array
rather than (for example) the List you've already built.
--
Eric.Sosman@sun.com