2016-05-30 120 views
-1

我不擅長泛型,但有人可以告訴我如何在下面的代碼中添加List<String>List<Object>?或者,我錯過了一些非常基本的東西。泛型:將`List <String>`添加到`List <Object>`

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

的方法是不適用的,因爲StringObjectList<String>不是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?? 

輸出

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


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

回答

1

您正在嘗試一個實際的List添加到List可能只包含String S,成功添加的每個單獨的項目,你將需要遍歷testObj列表並單獨添加它們

for (Object obj : testObj) { 
    testString.add(String.valueOf(obj)); 
} 
相關問題