How to convert List <Integer> to Integer [] in java?

I tried to convert ArrayListfrom IntegertoInteger[]

Integer[] finalResult = (Integer[]) result.toArray();

but i got an exception

Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.Integer;

Help me please.

+4
source share
5 answers

You need to use a version toArray()that takes a general argument:

Integer[] finalResult = new Integer[result.size()];
result.toArray(finalResult);

or, as a single line:

Integer[] finalResult = result.toArray(new Integer[result.size()]);
+7
source

You cannot use Listfor an array because it is Listnot an array. Here are two methods for converting a List<Integer>to Integer[].

List<Integer> list = Arrays.asList(1, 2, 3);
Integer[] arr = list.toArray(new Integer[list.size()]);
Integer[] arr2 = list.stream().toArray(Integer[]::new); // Java 8 only
+5
source

List.toArray() . List.toArray(T []):

Integer[] finalResult = (Integer[]) result.toArray(new Integer[result.size()]);
+2

.

Integer[] finalResult = new Integer[result.size()];
finalResult = result.toArray(finalResult);
+2

You can do this in several ways:

1st method

List<T> list = new ArrayList<T>();

T [] countries = list.toArray(new T[list.size()]);

Example:

List<String> list = new ArrayList<String>();

list.add("India");
list.add("Switzerland");
list.add("Italy");
list.add("France");

String [] countries = list.toArray(new String[list.size()]);

Second method

Foo[] array = new Foo[list.size()];
list.toArray(array); // fill the array

Third method

List<Integer> list = ...;
int[] array = new int[list.size()];
for(int i = 0; i < list.size(); i++) array[i] = list.get(i);

You can also find some code examples here - http://www.tutorialspoint.com/java/util/arraylist_toarray.htm or http://examples.javacodegeeks.com/core-java/util/list/java-list-to -array-example /

+2
source

Source: https://habr.com/ru/post/1617875/


All Articles