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

JavaGenerics

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

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>.

Solution 2 - Java

Any java collection is just a collection of objects be it string or other. The type argument is just sugar. Depending on situation, such as dealing with very large lists, you may just want to convert it - obviously risking mixing two different types of objects in the same list.

List<Object> objectList = (List)stringList;

And put a @SuppressWarning to get rid of nasties...

Solution 3 - Java

Personally, while both of the currently top rated answers are right in a way, I do not think any of them solves the problem in an elegant, reusable way, especially if you have to do this very often.

Suppose you have some old legacy code / dependency that you cannot change in any way (so that it would at least accept List<? extends Object> as @ReverendGonzo suggested in his comment. Suppose also, that you need to talk to this legacy module a lot.

I do not think either casting / copying all the time would be bearable on the long run. It makes your code either vulnerable to insidious bugs and hard to follow or slightly (or drastically) inefficient and hard-to-read.

To have readable and efficient production code, it is better to encapsulate the dirty part in a separate module which deals with the otherwise harmless but ugly cast.

class ProductionCode {
    public void doJob() {
        List<String> strings = Arrays.asList("pear", "apple", "peach");
        StringMagicUtils.dealWithStrings(strings);
    }
}

class StringMagicUtils {
    @SuppressWarnings("unchecked")
    public static void dealWithStrings(List<String> strings) {
        ExternalStringMagic.dealWithStringsAsObjects((List) strings);
    }
}

// Legacy - cannot edit this wonderful code below ˇˇ
class ExternalStringMagic {
    public static void dealWithStringsAsObjects(List<Object> stringsAsObjects) {
        // deal with them as they please
    }
}

Solution 4 - Java

If you are willing to convert to an unmodifiable List<Object>, you can simply wrap your list with Collections.unmodifiableList. This works because this static method has a proper wildcard type ? extends T for the element type of the wrapped list (where T is the type of the result list).

Note that, in most cases, creating an unmodifiable view is what you should do, otherwise objects of different types (other than String) may be added in the original list (which should only hold Strings).

Solution 5 - Java

This is pretty inefficient, but at least you don't have to write a lot of code~

List<String> stringList = new ArrayList<String>();
List<Object> objectList = Arrays.asList(stringList.toArray());

Solution 6 - Java

List<Object> ofObjects = new ArrayList<Object>(ofStrings);

as in:

import java.util.*;
class C { 
  public static void main( String[] args ) { 
     List<String> s = new ArrayList<String>();
     s.add("S");
     List<Object> o = new ArrayList<Object>(s);
     o.add( new Object() );
     System.out.println(  o );

  }
}

As an alternative you can try the addAll method, if the list of objects is an existing list.

Solution 7 - Java

model.class

public class Model {

private List<String> stringList = new ArrayList<>();

public List<String> getStringList() {
    return stringList;
}

public void setStringList(List<String> stringList) {
    this.stringList = stringList;
}

}

MainActivity

public class MainActivity extends AppCompatActivity {

Model model = new Model();
Spinner spinner;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    spinner=findViewById(R.id.spinner);

    List<String> itemList = new ArrayList<String>();
    itemList.add("item1");
    itemList.add("item2");
    itemList.add("item3");


   model.setStringList(itemList);

   
    ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, model.getStringList());
    dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    spinner.setAdapter(dataAdapter);

}

}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlexsView Question on Stackoverflow
Solution 1 - JavaErick RobertsonView Answer on Stackoverflow
Solution 2 - JavaMartin AlgestenView Answer on Stackoverflow
Solution 3 - JavaqbenView Answer on Stackoverflow
Solution 4 - JavaMichail AlexakisView Answer on Stackoverflow
Solution 5 - JavaRiley LarkView Answer on Stackoverflow
Solution 6 - JavaOscarRyzView Answer on Stackoverflow
Solution 7 - JavaMosayeb MasoumiView Answer on Stackoverflow