Converting a List Using CollectionUtils Raises an ArrayStoreException

Java Code:

Transformer TRANSFORM_TO_INTEGER = new Transformer() {
    public Object transform(Object input) {
        Integer i = new Integer((String) input);
        return i;
    }
};

String begin = "1,2,3,4,5";
List strList = Arrays.asList(StringUtils.split(begin, ","));
CollectionUtils.transform(strList, TRANSFORM_TO_INTEGER);

This code will raise an ArrayStoreException:

java.lang.ArrayStoreException
at java.util.Arrays$ArrayList.set(Arrays.java:2360)
at java.util.AbstractList$ListItr.set(AbstractList.java:488)
at org.apache.commons.collections.CollectionUtils.transform(CollectionUtils.java:434)

Why is this?

+3
source share
2 answers

ArrayStoreException occurs when an attempt to save an object with the wrong type is placed in an array.

What does the code do?

In the above code example, the method CollectionUtil.transformaccepts Collectionand performs the conversion of elements in place, which means that they Objectare extracted from the source Collection(for example List) and placed back into the same one Collection.

Transformer String Integer - - - , .

?

, CollectionUtil.transform Transformer Collection Collection, strList.

, List, Arrays.asList, String[], ArrayStoreException. , String[5]. ( Eclipse, JRE 6 Windows.)

?

, , , , , . ( Apache Commons Collection ), .

- List - List String s, Transformer.transform String.

?

Google Collections2.transform, Collection a Collection, Function.

generics, typeafe, , Collection, , .

+5

Arrays.asList , . API :

public static <T> List<T> asList(T... a) {
    return new ArrayList<T>(a);
}

StringUtils.split String[], Arrays.asList. , String.

CollectionUtils 2 :

  • - . transform() . Collection, (, ArrayList), , . , .

  • . . . collect() . collect() , , .

, , 2- collect().

+1

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


All Articles