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.
Add Items. Once a set is created, you cannot change its items, but you can add new items. To add one item to a set use the add() method.
The add() method adds a given element to a set.
Sets can be joined in Python in a number of different ways. For instance, update() adds all the elements of one set to the other. Similarly, union() combines all the elements of the two sets and returns them in a new set. Both union() and update() operations exclude duplicate elements.
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With