开发者

java casting a list

Let's say I had:

protected void performLogic(List<Object> docs) {
  ...
}

In the 开发者_如何转开发code where I'm going to be calling this method, I have a List<String> list. I want to call performLogic, passing this list. But it won't work because the lists are 2 different types:

public void execute() {
    List<String> docs = new ArrayList<String>();
    performLogin(docs);  // won't work
}

I tried casting to List<Object> also, but that won't work either.

So is the only way to do this is to make a new ArrayList of Object and just add the values and then pass it? Just seems cumbersome. I wondered if there was a better way to do it.

Thanks.


Its silly but you have to say T extends Object

protected static <T extends Object> void performLogic(List<T> docs)

Oh and its if part of a public API you can do this trick:

performLogic((List) var);

Just be careful as it will fail during runtime if var isn't an List of Objects. But lucky for you it is.


I think having List<Object> is a bad pattern since it really isn't that much better than List without generics. Generics are useful when you want to enforce type-safety in complex objects. As such they are really useful for enforcing type-safety in data structures.

You need to look at your algorithm and decide if you really want to accept a list of Object. That aside, can also forcibly cast it, but then you would be completely disregarding type safety.


If you do not add elements to the docs, you can change API to

protected void performLogic(List<?> docs);

All previous code that uses performLogic will continue to compile.


This would work as well (though bypassing typesafety):

performLogic((List)docs);


If the list doesn't need to be modified within performLogic you can use Collections.unmodifiableList to safely cast the list. Ex:

performLogic(Collections.unmodifiableList(docs));

To understand why this works you have to first understand why you can't just pass in docs as-is. The reason for that is a List can have any instance of object added to it (for instance an Integer). If the List reference were used later there would be an error because the Integer added to the list couldn't be cast to String. Making the list unmodifiable prevents this possibility so it is then safe to pass an unmodifiable List as a List.


The correct solution would be to try and have that broken API fixed. Using List<Object> as parameter is simply a misuse of Generics.

Until the API improves, you can cast to the raw type:

performLogin((List)docs);

It will still result in a compiler warning, though.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜