1

I want to cast a list of String to a list of Object but it caused a compile error. List<String> stringList = new ArrayList<>(); List<Object> objectList = (List<Object>)stringList; I may fill the objectList with stringList manually but I want to find a simpler and cleaner syntax.

lolacoco
  • 101
  • 8
  • 3
    This is also an [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). Explain *what* you're trying to do, not just how. – chrylis -cautiouslyoptimistic- Jul 25 '19 at 17:44
  • If you enable compiler warnings (which you should), the compiler will tell you that you are doing something bad. objectList and stringList are the same List. What happens to stringList if you do `objectList.add(Integer.valueOf(5))`? – VGR Jul 26 '19 at 01:15

4 Answers4

2

You can pass the stringList to the constructor of objectList or call addAll after creating it

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

///Or
objectList = new ArrayList<>();
objectList.addAll(stringList);
tiboo
  • 8,213
  • 6
  • 33
  • 43
2

Pass the List as a parameter to the constructor of a new ArrayList

  List<String> stringList = new ArrayList<>();
  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

Sachin Muthumala
  • 775
  • 1
  • 9
  • 17
0
List<Object> objectList = stringList.stream().map(s -> (Object) s).collect(Collectors.toList());

This should provide the solution you need.

0

The basic problem here is that while Object is a base class of String, when used in generics, AnyClass<Object> is not a base class to AnyClass<String>. That is why you cannot simply cast List<String> to List<Object>. However, each of the elements of List<String> can individually be added to a List<Object>, since then you are simply assigning a String to a referring object of type Object. Thus, a simple solution is

List<Object objectList = new ArrayList<>();
for(String str : stringList) objectList.add(str);
Vineet
  • 346
  • 6
  • 18