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

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


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


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

Tags:

Java

Generics