Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 449
dee Avatar asked Nov 22 '11 16:11

dee


People also ask

How do I turn a list of objects into strings?

To convert a list to a string, use Python List Comprehension and the join() function. The list comprehension will traverse the elements one by one, and the join() method will concatenate the list's elements into a new string and return it as output.

How do you convert a list element to a String in Java?

The toString() method on a list returns a string that is surrounded by square brackets and has commas between items. The idea is to get rid of square brackets using the substring() method and comma and space replace using the replaceAll() method.

Can we convert object to String in Java?

We can convert Object to String in java using toString() method of Object class or String. valueOf(object) method. You can convert any object to String in java whether it is user-defined class, StringBuilder, StringBuffer or anything else.

How do you turn an ArrayList into a String?

To convert the contents of an ArrayList to a String, create a StringBuffer object append the contents of the ArrayList to it, finally convert the StringBuffer object to String using the toString() method.


2 Answers

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.

like image 64
Andy Thomas Avatar answered Oct 13 '22 00:10

Andy Thomas


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();
like image 27
Matt Ball Avatar answered Oct 12 '22 23:10

Matt Ball