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;
}
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);
© 2024 OneMinuteCode. All rights reserved.