Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Enumerable.Cast() like C#?

Is there an equivalent in Java 1.5 to Enumerable.Cast() from C#? I want to assign an ArrayList<MyType> to a variable declared as List<Object>. Eclipse grumbles "Type mismatch: cannot convert from ArrayList<MyType> to List<Object>". I was just using List and ArrayList without generics but the compiler warns about that, and I wanted to clean up some warnings.

like image 351
Sarah Vessels Avatar asked Dec 02 '25 12:12

Sarah Vessels


1 Answers

It would be unsafe to cast that if you were going to add to the list. However, if you only want to fetch from the list you can use:

ArrayList<MyType> specificList = new ArrayList<MyType>();
List<? extends Object> generalList = specificList;

Or closer to Enumerable.Cast would be to use Iterable:

Iterable<? extends Object> generalIterable = specificList;

It's a shame that you even need to specify the wildcard here (I was surprised that you did) given that Iterable is a "read only" interface.

For a lot more information on Java generics, see the Java Generics FAQ.

like image 113
Jon Skeet Avatar answered Dec 04 '25 03:12

Jon Skeet