简体   繁体   English

在创建时向集合添加元素

[英]Adding elements to a set on creation

How can I create a Set in java, and then add objects to it when it is constructed. 如何在java中创建Set,然后在构造时向其中添加对象。 I want to do something like: 我想做的事情如下:

testCollision(getObject(), new HashSet<MazeState>(){add(thing);});

But that doesn't seem quite right. 但这似乎并不合适。

Since Java 7 , to instantiate a single-element , immutable Set, you can use: Java 7开始 ,要实例化单元素不可变集合,您可以使用:

Collections.singleton(thing);

Returns an immutable set containing only the specified object. 返回仅包含指定对象的不可变集。 The returned set is serializable. 返回的集是可序列化的。

Javadoc reference: Collections.singleton(T) - Javadoc参考:Collections.singleton(T)


In Java 8 you can instantiate a Set containing any number of your objects with the following, which is an adaptation of this answer : Java 8中,您可以使用以下内容实例化包含任意数量对象的Set,这是对此答案的修改:

Stream.of(thing, thingToo).collect(Collectors.toSet());

In Java 5 在Java 5中

new HashSet<MazeState>(Arrays.asList(thing));

Arrays.asList(thing) converts your thing to the list of one element, and from that list set is created. Arrays.asList(thing)将您的thing转换为一个元素的列表,并从该列表集创建。

For the reference: 供参考:
http://download.oracle.com/javase/6/docs/api/java/util/Arrays.html#asList(T...) http://download.oracle.com/javase/6/docs/api/java/util/Arrays.html#asList(T ...)

Since Java 9 you can also do it like this: 从Java 9开始,您也可以这样做:

 Set<String> immutableSet = Set.of("value1", "value2");
 Set<Integer> immutableInt = Set.of(1, 2);

 List<String> immutableList = List.of("item1", "item2");

 Map<String, String> immutableMap = Map.of("key1", "value1", "key2", "value2", "key3", "value3");

Observe that any Sets/Maps/Lists created this way will be immutable (if my naming convention didn't convince you ;) 请注意,以这种方式创建的任何集/映射/列表都是不可变的(如果我的命名约定没有说服你;)

You can use double-braces: 你可以使用双括号:

testCollision(getObject(), new HashSet<MazeState>(){{ add(obj1); add(obj2);}};

or: 要么:

Set<String> set = new HashSet<String>(){{
  add("hello");
  add("goodbye");
}};

This is called double-brace initialization, and it's one of the lesser known features of Java. 这称为双括号初始化,它是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类:

ImmutableSet.of(new MazeState(), new MazeState());

Other answers are correct but want to add one more way .using initializer block 其他答案是正确的,但想添加一个方法。使用初始化程序块

new HashSet<MazeState>() {

            {
                add(new MazeState());
                add(new MazeState());
            }
        };

您可以使用com.google.common.collect的util方法,这是一个非常好的方法: Sets.newHashSet("your value1", "your valuse2");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM