Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Convert List<String> to List<Object>

Tags:

java

generics

I want to convert List<String> to List<Object>.

One of the existing methods is returning List<String> and I want to convert it to List<Object>. Is there a direct way in Java other then iterating over and converting element by element?

like image 556
Alexs Avatar asked Nov 26 '10 19:11

Alexs


People also ask

How do you convert a list of strings to a list of objects?

Any Collection can be passed as an argument to the constructor as long as its type extends the type of the ArrayList , as String extends Object . The constructor takes a Collection , but List is a subinterface of Collection , so you can just use the List<String> . Show activity on this post.

Can we convert list to object in Java?

Yes. ArrayList has a toArray() method.


1 Answers

Pass the List<String> as a parameter to the constructor of a new ArrayList<Object>.

List<Object> objectList = new ArrayList<Object>(stringList); 

Any Collection can be passed as an argument to the constructor as long as its type extends the type of the ArrayList, as String extends Object. The constructor takes a Collection, but List is a subinterface of Collection, so you can just use the List<String>.

like image 53
Erick Robertson Avatar answered Oct 04 '22 21:10

Erick Robertson