java - cast List to ArrayList -


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

Popular posts from this blog

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -

javascript - firefox memory leak -

Trying to import CSV file to a SQL Server database using asp.net and c# - can't find what I'm missing -