HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavaCritical

How can I convert List<Integer> to int[] in Java?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
howjavaintegerintconvertlistcan

Problem

How can I convert a List to int[] in Java?

I'm confused because List.toArray() actually returns an Object[], which can be cast to neither Integer[] nor int[].

Right now I'm using a loop to do so:

int[] toIntArray(List list) {
  int[] ret = new int[list.size()];
  for(int i = 0; i < ret.length; i++)
    ret[i] = list.get(i);
  return ret;
}


Is there's a better way to do this?

This is similar to the question
How can I convert int[] to Integer[] in Java?.

Solution

Unfortunately, I don't believe there really is a better way of doing this due to the nature of Java's handling of primitive types, boxing, arrays and generics. In particular:

  • List.toArray won't work because there's no conversion from Integer to int



  • You can't use int as a type argument for generics, so it would have to be an int-specific method (or one which used reflection to do nasty trickery).



I believe there are libraries which have autogenerated versions of this kind of method for all the primitive types (i.e. there's a template which is copied for each type). It's ugly, but that's the way it is I'm afraid :(

Even though the Arrays class came out before generics arrived in Java, it would still have to include all the horrible overloads if it were introduced today (assuming you want to use primitive arrays).

Context

Stack Overflow Q#960431, score: 265

Revisions (0)

No revisions yet.