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

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

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.

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();

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

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?

Leave a Reply

Your email address will not be published. Required fields are marked *