Casting question

L

laredotornado

Hi,

I'm using Java 6. If I have a class A, and a subclass B that extends
A, how can I cast a List<B> from a return type, List<A>? That is, I
have

List<B> myList = (List<B>)
DataInterface.getRandomizedResults(DataInterface.NEW_SEARCH, params);

The "DataInterface.getRandomizedResults" returns List<A>, however I am
guaranteed that all the elements in the List are of class B. As you
know the above results in a compile error and I'm trying to figure out
an elegant way to convert the data.

Thanks, - Dave
 
L

Lew

Hi,

I'm using Java 6.  If I have a class A, and a subclass B that extends
A, how can I cast a List<B> from a return type, List<A>?  That is, I
have

List<B> myList = (List<B>)
DataInterface.getRandomizedResults(DataInterface.NEW_SEARCH, params);

The "DataInterface.getRandomizedResults" returns List<A>, however I am
guaranteed that all the elements in the List are of class B.  As you
know the above results in a compile error and I'm trying to figure out
an elegant way to convert the data.

http://download.oracle.com/javase/tutorial/extra/generics/index.html
in particular
http://download.oracle.com/javase/tutorial/extra/generics/subtype.html

Also
http://java.sun.com/docs/books/effective/generics.pdf
http://www.ibm.com/developerworks/java/library/j-jtp04298.html /et
seq./

It's all about what Java's generics and its type system assert.

You cannot aver that (B sub A) => (Foo<B> sub Foo<A>).

You can aver that (B sub A) => (Foo<B> sub Foo<? extends A>).

(I used "sub" for "is a subtype of".)
 
T

Tom Anderson

I'm using Java 6. If I have a class A, and a subclass B that extends A,
how can I cast a List<B> from a return type, List<A>? That is, I have

List<B> myList = (List<B>)
DataInterface.getRandomizedResults(DataInterface.NEW_SEARCH, params);

The "DataInterface.getRandomizedResults" returns List<A>, however I am
guaranteed that all the elements in the List are of class B. As you
know the above results in a compile error and I'm trying to figure out
an elegant way to convert the data.

You can say:

List<B> myList = (List<B>)(List)whatever();

But you should feel bad as you do this.

You could write a little function like:

<P, Q> List<Q> cast(List<P> list, Class<Q> elementType) {
List<Q> castList = new ArrayList<Q>(list.size());
for (P element: list) castList.add(elementType.cast(element));
return castList;
}

Which would give you runtime safety.

I don't suppose you have any control over the definition and
implementation of DataInterface.getRandomizedResults, do you?

tom
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,777
Messages
2,569,604
Members
45,206
Latest member
SybilSchil

Latest Threads

Top