Java: Is it possible to convert a list of objects to a list of strings [] and vice versa?

Is this possible if you do not go through the list and draw objects?

Do I also need to convert List<Object> to List<T> (T = predefined object), if possible?

Edit: for clarification, I'm trying to use List<Object> as the return type of a class method, which is widely used in my code.

+6
source share
4 answers

Not. This is simply a false conversion, because not all Object are String[] .


You could define this for yourself in two lines of code.


Edit

It looks like you need to write a more general method. Something like that:

 public <T> List<T> getGenericList() { return new ArrayList<T>(); } 

This can return List<String[]> like this:

 List<String[]> listOfStringArr = getGenericList(); 
+6
source

Actually, this is possible due to 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 that it is a good idea. This works during type checking of parameterizable types at compile time. If your List contains objects other than the type you expect, unexpected results may occur.

+9
source

Not. What if the Object in the first list is actually not T ?

In this case, you can try to make List<Object> to List<T> (be prepared for exceptions).

/ e1
I do not know the specifics of your code, but it seems that creating a common method would be useful for you.

0
source

This is not possible by definition. All classes in java extend Object. A list of objects can theoretically contain elements of any type that you want. How do you want to convert something to a specific type T ?

0
source

Source: https://habr.com/ru/post/902124/


All Articles