-1

In Java is there a way to cast the following:

ArrayList<IMyType> list

into

ArrayList<MyType>

if

MyType implements IMyType

?

marc wellman
  • 5,808
  • 5
  • 32
  • 59

5 Answers5

5

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>
Pshemo
  • 122,468
  • 25
  • 185
  • 269
1

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;
Keerthivasan
  • 12,760
  • 2
  • 32
  • 53
1

If you're certain that all IMyTypes 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.

Xavi López
  • 27,550
  • 11
  • 97
  • 161
  • Thank you very much .. this is exactly what I was looking for. Thank you also for advise regarding type-safety. My particular problem is that I get an ArrayList out of a Java RMI method which is of type `ArrayList`. Then I want to use this list but without the link to the RMI-type any more (which is `IMyTxpe`) and instead use the internal representation of the list elements - which is, `MyType`. – marc wellman Jan 30 '14 at 10:54
0

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);
 }
Ruchira Gayan Ranaweera
  • 34,993
  • 17
  • 75
  • 115
0

You can do cast in this case: (Inteder extends Number)

List<IMyType> list1 = new ArrayList<>();
List<? extends IMyType> list2 = new ArrayList<>();

list2 = list1;
Ashot Karakhanyan
  • 2,804
  • 3
  • 23
  • 28