2016-05-30 13 views
-1

私はジェネリックスが良くないですが、List<String>を以下のコードにList<String>に追加する方法を教えてもらえますか? または、私は非常に基本的なものを逃しています。ジェネリック: `リスト<String>`を `リスト<Object> 'に追加

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

StringObjectしかし List<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?? 

あなたが唯一成功し、個々の項目を追加するために、String Sを含むことがListに実際Listを追加しようとしている出力

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


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

答えて

1

、あなたはをループにする必要がありますtestObjリストを個別に追加してください。

for (Object obj : testObj) { 
    testString.add(String.valueOf(obj)); 
} 
関連する問題