-1

I am not good at Generics but can someone let me know how am I able to add List<String> to List<Object> in the below code? Or, am I missing out something very fundamental.

https://stackoverflow.com/a/20356096/5086633

The method is not applicable because String is an Object but List<String> is not a List<Object>.

     public static void main(String args[]) {

                List<Object>  testObj = new LinkedList<Object>();
                List<String>  testString = new LinkedList<String>();
                testObj.add("TestObjValue1");
                testObj.add("TestObjValue2");
            testObj.add("TestObjValue3");
            testObj.add("TestObjValue4");
            testString.add("TestStrValue1");
            testString.add("TestStrValue2");
            testString.add("TestStrValue3");
            testString.add("TestStrValue4");

            System.out.println(testObj);

    testObj.addAll(testString);

    System.out.println(testObj);

//testString.add(testObj);  --> Compile time Error

//testObj stores reference of type Object
//testString stores reference of type String
//so a String type List reference can store String type alone
//However Object type List ref variable can store Object and its subclasses??

Output

[TestObjValue1, TestObjValue2, TestObjValue3, TestObjValue4, 
[TestStrValue1, TestStrValue2, TestStrValue3, TestStrValue4]]


[TestObjValue1, TestObjValue2, TestObjValue3, TestObjValue4,
[TestStrValue1, TestStrValue2, TestStrValue3, TestStrValue4],
TestStrValue1, TestStrValue2, TestStrValue3, TestStrValue4]
Community
  • 1
  • 1
yeppe
  • 679
  • 1
  • 11
  • 43

1 Answers1

1

You are trying to add an actual List to the List that may only contain Strings, to successfully add each individual item, you will need to loop through the testObj list and add them individually

for (Object obj : testObj) {
    testString.add(String.valueOf(obj));
}
epoch
  • 16,396
  • 4
  • 43
  • 71