【问题标题】:Changing the type of an ArrayList [duplicate]更改 ArrayList 的类型 [重复]
【发布时间】:2017-10-09 20:07:28
【问题描述】:

问题基本上在于这个,我们创建了一个 Object ArrayLists 数组,因为我们不完全知道我们将在那里保存什么,但我们知道如何(我们必须这样做),所以默认在构造函数方法上创建将其初始化为
private List<Object> collection 但稍后某些输入会更改它,例如将其更改为字符串,因此该位置上的 AL 应该类似于 collection[i] = new ArrayList<String>() 但编译器说 ArrayList<String> cannot be converted into ArrayList<Object>甚至认为我很确定 String、Integer 等继承自 Object
谁能告诉我我做错了什么?

【问题讨论】:

  • collection[i] 是干什么用的?只需 add 收藏
  • collection[] 是将被 ArrayLists 填充的数组,但它们拒绝更改类型
  • 为什么不把List<Object>改成List<String>呢?还是ArrayList<String>ArrayList<Object>?它们必须是相同的类型,否则需要使用边界,例如List<? extends Object>

标签: java list object arraylist


【解决方案1】:

1) collection[i] 是一个数组

2) 如果你想这样写:

List<Object> collection; collection = new ArrayList<String>();

您将收到incompatible types: ArrayList&lt;String&gt; cannot be converted to List&lt;Object&gt;

您不能将字符串转换为对象。如果你想要它,你需要将它创建为一个字符串列表。如果你不知道你需要什么类型,就在你知道的时候创建它。如果是用户选择它,请像这样进行切换:

switch (entry) {
        case 1: {
            List<String> collection = new ArrayList<>();
            break;
        }
        case 2: {
            List<Integer> collection = new ArrayList<>();
            break;
        }
        case 3: {
            List<Character> collection = new ArrayList<>();
        }

    }

【讨论】:

    猜你喜欢
    • 2016-06-15
    • 2019-11-30
    • 1970-01-01
    • 2014-06-12
    • 1970-01-01
    • 1970-01-01
    • 2014-06-07
    • 1970-01-01
    • 2014-01-07
    相关资源
    最近更新 更多