在创建时将元素添加到集合中
如何在java中创建一个Set,然后在构造时向其中添加对象。我想做这样的事情:
testCollision(getObject(), new HashSet<MazeState>(){add(thing);});
但这似乎不太正确。
How can I create a Set in java, and then add objects to it when it is constructed. I want to do something like:
testCollision(getObject(), new HashSet<MazeState>(){add(thing);});
But that doesn't seem quite right.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
在 Java 5 中,
Arrays.asList(thing)
将您的thing
转换为一个元素的列表,并从该列表创建集合。供参考:
http://download .oracle.com/javase/6/docs/api/java/util/Arrays.html#asList(T...)
In Java 5
Arrays.asList(thing)
converts yourthing
to the list of one element, and from that list set is created.For the reference:
http://download.oracle.com/javase/6/docs/api/java/util/Arrays.html#asList(T...)
从 Java 9 开始,您也可以这样做:
观察以这种方式创建的任何 Sets/Maps/Lists 将是不可变的(如果我的命名约定不能说服您;)
Since Java 9 you can also do it like this:
Observe that any Sets/Maps/Lists created this way will be immutable (if my naming convention didn't convince you ;)
您可以使用双大括号:
或:
这称为双大括号初始化,它是 Java 鲜为人知的功能之一。它的作用是使编译器创建一个匿名内部类,为您进行创建和操作(因此,例如,如果您的类是最终的,您就无法使用它。)
现在,话虽如此 - 我会鼓励您仅在确实需要简洁的情况下使用它。更明确地几乎总是更好,这样更容易理解您的代码。
You can use double-braces:
or:
This is called double-brace initialization, and it's one of the lesser known features of Java. What it does is cause the compiler to create an anonymous inner class that does the creation and manipulation for you (So, for example, if your class was final, you couldn't use it.)
Now, having said that - I'd encourage you only to use it in cases where you really need the brevity. It's almost always better to be more explicit, so that it's easier to understand your code.
如果您不介意不变性,那么您可以使用 Google Guava 的
ImmutableSet
类:If you don't mind immutability then you may use Google Guava's
ImmutableSet
class:您可以使用
com.google.common.collect
中的 util 方法,这是一个非常好的方法:Sets.newHashSet("your value1", "your valuse2");
You can use the util method from
com.google.common.collect
, that is a pretty nice one:Sets.newHashSet("your value1", "your valuse2");
其他答案是正确的,但想添加另一种方式。使用 初始化块
Other answers are correct but want to add one more way .using initializer block
从Java 7开始,要实例化单元素、不可变集,您可以使用:
在 Java 8 中,您可以使用以下内容实例化包含任意数量对象的 Set,这是 这个答案:
Since Java 7, to instantiate a single-element, immutable Set, you can use:
In Java 8 you can instantiate a Set containing any number of your objects with the following, which is an adaptation of this answer: