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.
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.
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.
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.
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.
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 Object
s are String[]
.
You could have determined this for yourself in 2 lines of code.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With