0

Is it possible to convert and Object[]array to and integer Array.

The reason I am asking is because I added integers to an ArrayList and then converted this into and Object[]array.

ArrayList<Integer> list = new ArrayList<Integer>();
Object[] arrayNumbers = list.toArray();

Which would be the best way of getting this into and int[]array? All I need to do is to sort these numbers. Can I sort all my numbers in this arraylist without converting it into an int[]array?

Kind regards

Arianule
  • 8,811
  • 45
  • 116
  • 174
  • "It depends how the sort is being done". (No, it is *not* required to have an `int[]` to sort a collection of integer objects; at the very least Integer implements Comparable.) –  Mar 28 '12 at 10:14
  • sorting is a different thing than converting a List into a int[] array. And the latter was already answered: http://stackoverflow.com/questions/3706470/convert-integer-list-to-int-array – Alonso Dominguez Mar 28 '12 at 10:17

5 Answers5

3

You should be doing this:

Integer[] arrayNumbers = list.toArray(new Integer[list.size()]);

If you just want to sort, simply use Collections.sort(list).

adarshr
  • 61,315
  • 23
  • 138
  • 167
3

You can sort the list using Collections.sort method instead of all the conversions.

MByD
  • 135,866
  • 28
  • 264
  • 277
1

You already have the list of integers in the variable list.

Iterate over list and keep a track of the index and add array[index] = i:

Algorithm not Java code, I'll leave that to you:

int index;

for (index =0; index <= list.Count(); index++) {
  array[index] = list[index];
}
adarshr
  • 61,315
  • 23
  • 138
  • 167
Darren
  • 68,902
  • 24
  • 138
  • 144
1

You could use the following code to sort your values

 Arrays.sort(arrayNumbers);
Chetter Hummin
  • 6,687
  • 8
  • 32
  • 44
1

You can sort the ArrayList using Collections.sort()

Collections.sort(list);
len
  • 335
  • 1
  • 5