In Java is there a way to cast the following:
ArrayList<IMyType> list
into
ArrayList<MyType>
if
MyType implements IMyType
?
In Java is there a way to cast the following:
ArrayList<IMyType> list
into
ArrayList<MyType>
if
MyType implements IMyType
?
If you are absolutely sure that your list
contains only instances of MyType
(or its subtypes) then you can do something like
@SuppressWarnings("unchecked")
List<MyType> myList = (List<MyType>) (List<?>) list;
This will first cast your list of IMyType
to list of any type <?>
which then you can cast to more precise type. But be sure to use it only if your list
contains instances of MyType
and nothing else.
Anyway this approach is very rarely used and in most cases can be replaced with
List<? extends IMytype>
or
List<? super MyType>
No, This is because ArrayList<MyType>
is not a subtype of ArrayList<IMyType>
. Just only MyType
is the subtype of IMyType
. What you can do is you can iterate the ArrayList<IMyType>
and get the IMyType
object and then type cast it to MyType
instance like
IMyType iMyType = ..
MyType myType = (MyType)iMyType;
If you're certain that all IMyType
s in the List
are MyType
, you could force an unchecked conversion type variable assignment:
List<IMyType> l1;
List rawList = l1;
List<MyType> l2 = rawList;
Or
List<IMyType> l1;
List<MyType> l2 = (List) l1;
Note: this will produce a ClassCastException
at runtime if you retrieve an element from l2
(for instance, iterating in an [enhanced] for
loop) and it isn't a MyType
.
Keep in mind this is more a hack than a proper solution, and is completely bypassing type safety (which is what generics is about basically).
This could be hinting that something is not quite right with the modeling of the classes and/or how they are used.
You can try this. You can't directly cast ArrayList
. You can cast one by one
ArrayList<IMyType> list=new ArrayList<IMyType>();
ArrayList<MyType> list2=new ArrayList<MyType>();
for(IMyType i:list){
list2.add((MyType)i);
}
You can do cast in this case: (Inteder
extends Number
)
List<IMyType> list1 = new ArrayList<>();
List<? extends IMyType> list2 = new ArrayList<>();
list2 = list1;