开发者

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. I want to d开发者_运维百科o 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:

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


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


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


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.


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

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


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

new HashSet<MazeState>() {

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜