Generic type toArray and asList

I am trying to understand generics and I intentionally want to throw a classcastexception, however instead I get an arraystoreexception on the first try.

static <E> E reduce(List<E> list, Function<E> f, E initVal) { E[] snapshot = (E[]) list.toArray(); Object[] o = snapshot; o[0] = new Long(1); E result = initVal; for (E e : snapshot) result = f.apply(result, e); return result; } private static final Function<Integer> SUM = new Function<Integer>(){ public Integer apply(Integer i1, Integer i2) { return i1 + i2; } }; public static void main(String[] args) { List<Integer> intList = Arrays.asList(2, 7); System.out.println(reduce(intList, SUM, 0)); } 

In the second attempt .. I am correctly getting a ClassCastException using this ...

 public static void main(String[] args) { List<Integer> intList1 = Arrays.asList(2, 7); List<Integer> intList = new ArrayList<Integer>(intList1); System.out.println(reduce(intList, SUM, 0)); } 

What is the difference?

+7
source share
2 answers

It seems to me that the List instance created by Arrays.asList () does not properly implement the contract of the toArray () method. From List.toArray () javadoc:

 Note that toArray(new Object[0]) is identical in function to toArray(). 

However, pay attention to the following test:

 public static void main(String... args) { System.out.println(Arrays.asList(2, 7).toArray()); System.out.println(Arrays.asList(2, 7).toArray(new Object[0])); } 

and conclusion:

 [Ljava.lang.Integer;@3e25a5 [Ljava.lang.Object;@19821f 

Note that according to javadoc, toArray () should create an array of type Object [], but instead, Arrays.<E>asList().toArray() creates an array of type E [].

The reason you get an ArrayStoreException is because your array is of type Integer [] when it must be of type Object [].

+3
source

I do not know why you are creating an array. Just do the following:

 static <E> E reduce(List<E> list, Function<E> f, E initVal) { for (E e : list) initVal = f.apply(initVal, e); return initVal; } 

See: KISS Principle

0
source

All Articles