Can I change List<Integer> to int[]?

Asked 2 years ago, Updated 2 years ago, 111 views

I'm learning Java. Can I change the list to int[]? There is a method called List.toArray(), but the return data type is Object[]. I want to get an Integer[] or an int[] What should I do? Right now, I'm just turning the repetitive sentences and putting them in one by one. Is there a better way?

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

java array collections

2022-09-21 19:03

1 Answers

There's no direct way to change the list to int[] because of the nature of dealing with the basic types of Java Boxing, the array, the generic type. There is a way to write a public library, such as Ints.toArray in Guava.

List<Integer> list = ...
int[] ints = Ints.toArray(list);


2022-09-21 19:03

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.