麻烦初始化List< Object []>使用Arrays.asList [英] trouble initialize List<Object[]> Using Arrays.asList

查看:58
本文介绍了麻烦初始化List< Object []>使用Arrays.asList的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

初始化列表时,我可以执行以下操作:

When I initialize List, I am able to do this:

List<Object[]> foo = new ArrayList<>();
foo.add(new Object[]{816, "foo", 2.6});

但是当我想使用 Arrays.asList 简化它时:

But when I want to simplify it using Arrays.asList:

List<Object[]> bar = Arrays.asList(new Object[]{"bar", 286});

它无法编译并显示错误:

It cannot compile with error:

incompatible types: inference variable T has incompatible bounds
equality constraints: java.lang.Object[]
lower bounds: java.lang.Object

为什么不能正确进行类型推断以及如何解决呢?

Why it cannot do the type inference right and how to fix this?

推荐答案

请记住, ... 只是数组参数的语法糖.您可以使用

Remember that ... is just syntactic sugar for an array parameter. You can call a method with a variadic parameter foo(Object...) either using

foo("hello", 1);

foo(new Object[]{"hello", 1});

因为编译器还是会构造第二种形式.

since the compiler constructs the second form anyway.

因为在编译器推断类型时不考虑接收器类型,所以它查看 Arrays.asList(new Object [] {"bar",286})并认为您的意思是创建 Object 的列表,而不是 Object [] 的单例列表.

Because the receiver type isn't considered when the compiler infers types, it looks at Arrays.asList(new Object[]{"bar", 286}) and thinks that you mean to create a list of Object, not a singleton list of Object[].

使用现有语法的最简单方法是添加一个显式类型参数:

The easiest way with your existing syntax is just to add an explicit type parameter:

List<Object[]> bar = Arrays.<Object[]>asList(new Object[]{"bar", 286});

添加< Object []> 会告诉编译器T应该是什么.

Adding the <Object[]> tells the compiler what T should be.

或者,如果您不需要可变的列表:

Or, if you don't need the list to be mutable:

List<Object[]> bar = Collections.singletonList(new Object[]{"bar", 286});

这篇关于麻烦初始化List&lt; Object []&gt;使用Arrays.asList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆