在创建时将元素添加到集合中

发布于 2024-10-10 15:24:43 字数 163 浏览 2 评论 0原文

如何在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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

趴在窗边数星星i 2024-10-17 15:24:44

在 Java 5 中,

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

Arrays.asList(thing) 将您的 thing 转换为一个元素的列表,并从该列表创建集合。

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

In 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.

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

只有影子陪我不离不弃 2024-10-17 15:24:44

从 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");

观察以这种方式创建的任何 Sets/Maps/Lists 将是不可变的(如果我的命名约定不能说服您;)

Since Java 9 you can also do it like this:

 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 ;)

唯憾梦倾城 2024-10-17 15:24:44

您可以使用双大括号:

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

或:

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

这称为双大括号初始化,它是 Java 鲜为人知的功能之一。它的作用是使编译器创建一个匿名内部类,为您进行创建和操作(因此,例如,如果您的类是最终的,您就无法使用它。)

现在,话虽如此 - 我会鼓励您仅在确实需要简洁的情况下使用它。更明确地几乎总是更好,这样更容易理解您的代码。

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. 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.

迷爱 2024-10-17 15:24:44

如果您不介意不变性,那么您可以使用 Google Guava 的 ImmutableSet 类:

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

If you don't mind immutability then you may use Google Guava's ImmutableSet class:

ImmutableSet.of(new MazeState(), new MazeState());
好菇凉咱不稀罕他 2024-10-17 15:24:44

您可以使用 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");

童话里做英雄 2024-10-17 15:24:44

其他答案是正确的,但想添加另一种方式。使用 初始化块

new HashSet<MazeState>() {

            {
                add(new MazeState());
                add(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());
            }
        };
情深缘浅 2024-10-17 15:24:43

Java 7开始,要实例化单元素不可变集,您可以使用:

Collections.singleton(thing);

返回仅包含指定对象的不可变集。返回的集合是可序列化的。

Javadoc参考:Collections.singleton(T)


Java 8 中,您可以使用以下内容实例化包含任意数量对象的 Set,这是 这个答案

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

Since Java 7, to instantiate a single-element, immutable Set, you can use:

Collections.singleton(thing);

Returns an immutable set containing only the specified object. The returned set is serializable.

Javadoc reference: 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:

Stream.of(thing, thingToo).collect(Collectors.toSet());
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文