为什么要收集文字? [英] Why collection literals?

查看:181
本文介绍了为什么要收集文字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好的Java程序员。

Hi fellow Java programmers.

从Java 7的各种在线文章我已经知道Java 7将有收集文字 1 < sup>如下:

From the various online articles on Java 7 I have come to know that Java 7 will be having collection literals1 like the following:

List<String> fruits = [ "Apple", "Mango", "Guava" ];
Set<String> flowers = { "Rose", "Daisy", "Chrysanthemum" };
Map<Integer, String> hindiNums = { 1 : "Ek", 2 : "Do", 3 : "Teen" }; 

我的问题是:

不可能在所有集合类中提供 c>的静态方法,可以使用如下:

1] Wouldn't it have been possible to provide a static method of in all of the collection classes which could be used as follows:

List<String> fruits = ArrayList.of("Apple", "Mango", "Guava");

IMO这看起来和文字版本一样好,也相当简洁。为什么他们必须发明一个新的语法( EDIT: By'new'我的意思是Java的新。)

IMO this looks as good as the literal version and is also reasonably concise. Why then did they have to invent a new syntax ( By 'new' I mean 'new to Java'.)?

2 ]当我说 List< String>果实= [苹果,芒果,番石榴]; 什么列表 ArrayList 还是 LinkedList 还是其他?

2] When I say List<String> fruits = [ "Apple", "Mango", "Guava" ]; what List would I actually get? Would it be ArrayList or LinkedList or something else?

1 正如注释中提到的,收集文字不会对Java 7做裁剪,以下是来自Brian Goetz的电子邮件 Oracle开发人员,总结了不包括此功能的原因;这里是提案本身。)

1 As noted in the comments, collection literals did not make the cut for Java 7, nor indeed Java 8. (Here's an email from Brian Goetz, an Oracle developer, summarizing the rationale for not including this feature; and here is the proposal itself.)

推荐答案

问题2的回答:

final List<Integer> piDigits = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 9];

给您一个不可变的列表。

gives you an immutable list.

这个提议的整个想法,子类型不能被指定。编译器根据右侧的集合选择合适的实现。

The whole idea of this proposal that the subtype cannot be specified. The compiler chooses a suitable implementation depending on the collection on the right-hand side.

在这里阅读详情:提案:收藏文字

回答问题1:是的。这是一个风格问题。

Answer to question 1: yes it would have. It's a matter of style.

这篇关于为什么要收集文字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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