如何在Java 7中使用收集文字? [英] How do I use collection literals in Java 7?
问题描述
我试过下面这行:
Map<Character, Color> map={new Character('r'):Color.red,new Character('b'):Color.black};
< ';'expected 。
我将Source / Binary格式设置为JDK 7,平台设置为JDK 1.7,还有其他需要做的事吗?
I've set the Source/Binary format as 'JDK 7'and the platform to 'JDK 1.7', is there anything else I need to do?
推荐答案
Java 7不支持收集文字。 他们计划在Java 8。他们没有使它甚至进入Java 8,如这个问题讨论: Project Coin的集合增强功能将在JDK8中?
Java 7 does not support collection literals. They are planned for Java 8. They didn't make it even into Java 8 as discussed in this question: Are Project Coin's collection enhancements going to be in JDK8?
如果您只需要不可变的集合,请使用Google的 Guava 库。 ImmutableList
, ImmutableSet
和 ImmutableMap
有几个重载的工厂方法,甚至是创建集合的构建器:
You can use Google's Guava library if you need only immutable collections. ImmutableList
, ImmutableSet
and ImmutableMap
have several overloaded factory methods or even builders that make creating collections easy:
List<Integer> list = ImmutableList.of(1, 1, 2, 3, 5, 8, 13, 21);
Set<String> set = ImmutableSet.of("foo", "bar", "baz", "batman");
Map<Integer, String> map = ImmutableMap.of(1, "one", 2, "two", 3, "three");
EDIT
Java 9可能会添加类似于Guava的收集工厂方法:
Java 9 will probably add collection factory methods similar to those of Guava:
List.of(a, b, c);
Set.of(d, e, f, g);
Map.of(k1, v1, k2, v2)
Map.ofEntries(
entry(k1, v1),
entry(k2, v2),
entry(k3, v3),
// ...
entry(kn, vn)
);
这篇关于如何在Java 7中使用收集文字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!