【问题标题】:List of Objects filled with Arrays asList doesn't compile requires List of Serializable用数组填充的对象列表 asList 无法编译需要可序列化的列表
【发布时间】:2014-03-23 11:38:24
【问题描述】:

这是我正在尝试做的示例代码我正在尝试创建任何混合类型的对象列表 boolean array's/int array's/long array's float array's/int's/long's/boolean's/Strings

public List<Object> saveState() {
return Arrays.asList("potatoes", false, 11, null, new int[] {123, 44}, new float[] {66.331, 11.22}, boolean[] {false, false, true});
}

  required: List<Object>
  found:    List<INT#1>
  where INT#1,INT#2 are intersection types:
    INT#1 extends Object,Serializable,Comparable<? extends INT#2>
    INT#2 extends Object,Serializable,Comparable<?>

然后当使用实变量而不是硬编码值时。我收到此错误

required: List<Object>
found:    List<Serializable>

我想弄清楚如何转换 new Object[] {...} 编译没有问题,但它必须是另一个库的列表,我也需要传递值。

【问题讨论】:

    标签: java arrays object generics


    【解决方案1】:

    当您将不同的类型参数传递给期望所有类型参数都属于同一类型的方法时,就会出现类型推断的问题。然后编译器将类型参数推断为类型参数的所有常见超类型的交集。

    在您的情况下,您正在传递 - Stringbooleanintint[],等等......类型。当然,它们不适合所有类型中的单一类型。所以,推断的类型是:

    Object & Serializable & Comparable<?>
    

    因为这些是所有给定类型的超类型。

    如果您愿意,可以显式指定单个类型参数:

    public List<Object> saveState() {
        return Arrays.<Object>asList("potatoes", false, 11, null, new int[] {123, 44}, new float[] {66.331, 11.22}, boolean[] {false, false, true});
    }
    

    参考:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-23
      • 1970-01-01
      • 2017-02-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-02
      相关资源
      最近更新 更多