Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 do something like:

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

But that doesn't seem quite right.

like image 242
Dartoxian Avatar asked Jan 04 '11 16:01

Dartoxian


People also ask

Can you add things to a set in Python?

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.

Which method is used to add one element in the set?

The add() method adds a given element to a set.

How do you add two sets of elements in Python?

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.


1 Answers

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()); 
like image 117
fspinnenhirn Avatar answered Oct 03 '22 21:10

fspinnenhirn