我在这里阅读了一个关于使用ImmutableSet
Guava 的好例子.为了完整起见,此处报告了此示例:
public static final ImmutableSet<String> COLOR_NAMES = ImmutableSet.of(
"red",
"orange",
"yellow",
"green",
"blue",
"purple");
class Foo {
Set<Bar> bars;
Foo(Set<Bar> bars) {
this.bars = ImmutableSet.copyOf(bars); // defensive copy!
}
}
Run Code Online (Sandbox Code Playgroud)
问题是,我可以通过使用Java枚举获得相同的结果吗?
PS:这个问题在我的脑海中更加混乱!
我可以使用Java枚举获得相同的结果吗?
是的你可以.你试过吗?
仅供参考还有专门的版本ImmutableSet
保存枚举的常量 - Sets.immutableEnumSet
(内部使用EnumSet
).
一些例子(解释Wiki的例子):
public class Test {
enum Color {
RED, ORANGE, YELLOW, GREEN, BLUE, PURPLE;
}
static class Baz {
ImmutableSet<Color> colors;
Baz(Set<Color> colors) {
this.colors = Sets.immutableEnumSet(colors); // preserves enum constants
// order, not insertion order!
}
}
public static void main(String[] args) {
ImmutableSet<Color> colorsInInsertionOrder = ImmutableSet.of(
Color.GREEN, Color.YELLOW, Color.RED);
System.out.println(colorsInInsertionOrder); // [GREEN, YELLOW, RED]
Baz baz = new Baz(colorsInInsertionOrder);
System.out.println(baz.colors); // [RED, YELLOW, GREEN]
}
}
Run Code Online (Sandbox Code Playgroud)
编辑(OP评论后):
你想要ImmutableSet中的所有枚举常量吗?做就是了:
Sets.immutableEnumSet(EnumSet.allOf(Color.class));
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
10206 次 |
最近记录: |