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

2
  • "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.) Commented Mar 28, 2012 at 10:14
  • sorting is a different thing than converting a List<Integer> into a int[] array. And the latter was already answered: stackoverflow.com/questions/3706470/… Commented Mar 28, 2012 at 10:17

5 Answers 5

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).

Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

1

You could use the following code to sort your values

 Arrays.sort(arrayNumbers);

Comments

1

You can sort the ArrayList using Collections.sort()

Collections.sort(list);

Comments

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];
}

2 Comments

@adarshr did you event read my answer? I clearly state it's the algorithm not Java code.....why downvote?
Sorry, didn't notice. Reverted back.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.