英文:
Is it ok to omit diamond operator in recent java versions (8+)?
问题
使用Java 7时,我们可以使用钻石操作符:
List<String> list = new ArrayList<>();
现在我在一些最近的代码中看到人们省略了钻石操作符:
List<String> list = new ArrayList();
这是在更新的Java版本(Java 8+)中新增的一个新特性,可以省略钻石操作符吗?还是他们只是依赖于旧的原始ArrayList类型(由于向后兼容的原因而恰好可以工作,应该避免使用)?
英文:
With Java 7 we could use the diamond operator:
List<String> list = new ArrayList<>();
Now I am seeing in some recent codes people dropping the diamond operator:
List<String> list = new ArrayList();
Is this a new feature added in more recent java versions (Java 8+) to drop the diamond operator? Or they are simply relying on the raw old ArrayList type (which just happens to work for backward compatibility reasons, and should be avoided)?
答案1
得分: 2
根据我的看法,如果可能的话,您不应该省略它,尽管它能够工作。
省略它意味着使用原始类型。在运行时,这没有任何区别,因为泛型在编译时被擦除,但是您可能会因为 <Object>
类型不匹配而收到编译器警告和/或代码检查器警告/错误/失败。
如果您不知道类型或不想指定类型,仍然可以使用 <? extends Object>
。
问题是如果您想要做类似这样的事情:
List<String>[] data = new List<String>[16];
这不起作用,因为您不能轻易地实例化泛型数组。
在这种情况下,我会省略类型推断并忽略(抑制)(可能的)编译器警告。
@SuppressWarnings("unchecked")
List<String>[] data = new List[16];
但是,正如@vbezhenar在评论中提到的:
> 最好避免使用泛型类型的数组,而是使用类似于 List<List<String>>
的结构。
总的来说,与数组相比,List
更容易处理,尤其是在使用泛型时。
英文:
In my opinion, you should not omit it if possible but it works.
Ommitting it means using the raw type. At runtime, this makes no difference as generics are erased at compiletime but you may get compiler warnings and/or linter warnings/errors/fails because the <Object>
type does not fit.
If you don't know the type or don't want to specify it, you can still use <? extends Object>
.
The problem is if you want to do something like this:
List<String>[] data=new List<String>[16];
This does not work because you cannot instantiate arrays of generics easily.
In that case, I would leave out the type interference and ignore(suppress) the (possible) compiler warnings.
@SuppressWarnings("unchecked")
List<String>[] data=new List[16];
But, as @vbezhenar mentioned in the comments:
> It's better to avoid using arrays of generic types, just use something like List<List<String>>
for that.
In general, List
s are easier to deal with than arrays, especially if you use generics.
答案2
得分: 1
正确的语法(根据您的需求)是:
List<String> l1 = new ArrayList<>();
省略尖括号操作符意味着一个未限定的列表,这在底层当然是相同的,但会给您一个编译器警告。
未限定地使用它会违反编译时类型检查系统,并且与您用尖括号操作符声明的变量不一致,但如果正确使用,它将编译通过(并且如果操作正确,会工作)。这就是为什么会得到一个警告。
英文:
The correct syntax (for what you want) is:
List<String> l1=new ArrayList<>();
Omitting the diamond operator means an unqualified list, which (under the hood is the same, of course, but) will give you a compiler warning.
Using it unqualified works against the compile-time type-checking system, and is not in accordance with the variable you declare with the diamond operator, but it will compile (and work if you do it right). That's why you will get a warning.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论