3

Possible Duplicate:
How do you cast a List of objects from one type to another in Java?

Searched the internet a little, and found no nice way of doing it... My solution now is:

public class A {}
List<Object> obj = new ArrayList<Object>();
obj.add(new A());
// Ugly solution here:
List<A> a = (List<A>) (List) obj;

But this is quite ugly and gets a warning. No "official" way of doing this?

EDIT: To the guys who closed this: I was aware of the solution posted in How do you cast a List of objects from one type to another in Java? It is the same as the one I posted in my question (just adding the <?> after the first cast does exactly the same) I Was looking for something more "clean". In the direction of using the Class<?> clazz = listobj.get(0).getClass way of getting the class and casting to the correct class at runtime (but no idea if something like that works... Eclipse doesn't seem to like it anyway...)


So why isn't your list declared as

List<A> obj = new ArrayList<A>();

to begin with ?

It's really dangerous to do what you're trying to do. What you're saying is that your list contains As and subclasses thereof. But since it's originally a list of Objects (i.e. anything). You're likely to get a nasty surprise later on.

What that compiler error really means is that somewhere you have a design issue.

4

3 回答 3

8
List<Object> obj = new ArrayList<Object>();
obj.add(new A());

It is not the right way to write code. Basically you are creating a generic List and adding Object to it and it type unsafe and keep any Object type.

List<Object> obj = new ArrayList<Object>();
obj.add(new A());
obj.add(new String("str"));
obj.add(1);

It is recommended to create type-safe List like List<A> obj = new ArrayList<A>();

you can do this in such a way -

public <T>List<T> castCollection(List srcList, Class<T> clas){
    List<T> list =new ArrayList<T>();
    for (Object obj : srcList) {
    if(obj!=null && clas.isAssignableFrom(obj.getClass()))
        list.add(clas.cast(obj));
    }
    return list;
}
于 2013-01-08T09:41:47.230 回答
6

那么为什么你的列表没有被声明为

List<A> obj = new ArrayList<A>();

开始?

做你想做的事真的很危险。您的意思是您的列表包含As 及其子类。但因为它最初是一个Objects 列表(即任何东西)。以后你可能会得到一个令人讨厌的惊喜。

该编译器错误的真正含义是您在某个地方遇到了设计问题。

于 2013-01-08T09:38:29.363 回答
2

Perhaps the issue is that you want to put objects of different (but inheritance-related) types into the list? In that case, you read the Generics Tutorial, especially the parts about <? extends Something> and <? super Something>

Cheers,

于 2013-01-08T09:41:13.020 回答