【问题标题】:Generics : add `List<String>` to `List<Object>` [duplicate]泛型:将 `List<String>` 添加到 `List<Object>` [重复]
【发布时间】:2016-09-28 07:36:57
【问题描述】:

我不擅长泛型,但有人可以告诉我如何在下面的代码中将List&lt;String&gt; 添加到List&lt;Object&gt;? 或者,我是否遗漏了一些非常基本的东西。

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

该方法不适用,因为StringObjectList&lt;String&gt; 不是 List&lt;Object&gt;

     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]

【问题讨论】:

    标签: java generics collections


    【解决方案1】:

    您正在尝试将实际的List 添加到可能仅包含Strings 的List,要成功添加每个单独的项目,您需要遍历testObj 列表并单独添加它们

    for (Object obj : testObj) {
        testString.add(String.valueOf(obj));
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-22
      • 2018-07-17
      • 1970-01-01
      • 2012-12-26
      • 1970-01-01
      • 2017-11-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多