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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With