1

When I want to cast the ArrayList object in List reference that returned from the method:

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

The return type from the method asList is a List reference to ArrayList object, which means I can cast it to ArrayList reference. Such that :

String[] colors = { "black", "blue", "yellow" };
ArrayList<String> links = (ArrayList<String>) Arrays.asList(colors) ;

But this code made run-time error :

Exception in thread "main" java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList

Why it's happened?

Linus Caldwell
  • 10,908
  • 12
  • 46
  • 58
Aladdin
  • 221
  • 1
  • 3
  • 11

1 Answers1

4

Your assumption that you can cast it to ArrayList is not valid.

The ArrayList is concrete type that implement List interface. It is not guaranteed that method asList, will return this type of implementation.

In fact the used type is java.util.Arrays$ArrayList.

Using concrete class instead of interfaces. Can be recognized as bad practice. This approach is better when you have special type of class and you want to give a hint for future developer that this type is dedicated for the task.

But the API should exposed in the most abstract way. That is why the List was used.