Generics : add `List<String>` to `List<Object>`
本问题已经有最佳答案,请猛点这里访问。
我不擅长仿制药,但有人能告诉我如何在下面的代码中添加
https://stackoverflow.com/a/20356096/5086633
The method is not applicable because
String is anObject but
List is not aList .
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | 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?? |
产量
1 2 3 4 5 6 7 | [TestObjValue1, TestObjValue2, TestObjValue3, TestObjValue4, [TestStrValue1, TestStrValue2, TestStrValue3, TestStrValue4]] [TestObjValue1, TestObjValue2, TestObjValue3, TestObjValue4, [TestStrValue1, TestStrValue2, TestStrValue3, TestStrValue4], TestStrValue1, TestStrValue2, TestStrValue3, TestStrValue4] |
您试图将实际的