可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
Is this possible without going through the list and casting the objects?
I also need to convert List<Object>
to List<T>
(T = predefined Object) if it's possible?
Edit: for clarification, I'm trying to use List<Object>
as a return type of a class method that is widely used in my code.
回答1:
No. This is simply not a valid conversion, because not all Object
s are String[]
.
You could have determined this for yourself in 2 lines of code.
Edit
It sounds like you need to write the method more generically. Something like this:
public <T> List<T> getGenericList() { return new ArrayList<T>(); }
This can return a List<String[]>
like so:
List<String[]> listOfStringArr = getGenericList();
回答2:
Actually, this is possible, because of type erasure. You can convert a parameterized type to a raw type, and vice-versa.
List<Object> listO = new ArrayList<Object>( ); listO.add( "Foo" ); listO.add( "Bar" ); List listQ = listO; List<String> listS = (List<String>) listQ;
However, this does not mean this is a good idea. This works around compile-time type-checking of parameterized types. If your List contains objects other than the type you expect, unexpected results may occur.
回答3:
It is not possible by definition. All classes in java extend Object. List of Objects can theoretically contain elements of every type your want. How do you want to convert something to specific type T
?
回答4:
No. What if the Object
in the first list isn't actually T
?
That being said, you can try to cast List<Object>
to List<T>
(be prepared for exceptions).
/e1
I don't know the specifics of your code, but it sounds like creating a generic method would be beneficial to you.