java - cast List to ArrayList -
this question has answer here:
when want cast arraylist
object in list
reference returned method:
public static <t> list<t> aslist(t... a) { return new arraylist<>(a); }
the return type method aslist
list
reference arraylist
object, means can cast arraylist
reference. such :
string[] colors = { "black", "blue", "yellow" }; arraylist<string> links = (arraylist<string>) arrays.aslist(colors) ;
but code made run-time error :
exception in thread "main" java.lang.classcastexception: java.util.arrays$arraylist cannot cast java.util.arraylist
why it's happened?
your assumption can cast arraylist not valid.
the arraylist
concrete type implement list
interface. not guaranteed method aslist
, return type of implementation.
in fact used type java.util.arrays$arraylist
.
using concrete class instead of interfaces. can recognized bad practice. approach better when have special type of class , want give hint future developer type dedicated task.
but api should exposed in abstract way. why list
used.
Comments
Post a Comment