0 votes
1 view
in Java by (4.1k points)
edited by

I'm new to Java. How can i convert a List<Integer> to int[] in Java? I'm confused because List.toArray()actually returns an Object[], which can be cast to nether Integer[] or int[].

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

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

I'm sure there's a better way to do this.

2 Answers

0 votes
by (46.1k points)

You can try Streams in Java 8:-

int[] array = list.stream().mapToInt(i->i).toArray();

Example:

int[] toIntArray(List<Integer> list)  {

    int[] ret = new int[list.size()];

    int i = 0;

    for (Integer e : list)  

        ret[i++] = e;

    return ret;

}

To know more about Int[] click here.

0 votes
by (33.2k points)

The following terms would help you to understand things better:

  • List<T>.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).

There are some libraries that 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). 

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

Hope this answer helps you!

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...