Java: Can I convert List of Object to List of String[] and vice versa?

匿名 (未验证) 提交于 2019-12-03 08:46:08

问题:

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 Objects 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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!