In Java, you can add an element to a Set using the "add" method. The "add" method adds the specified element to the Set if it is not already present. If the Set already contains the element, the "add" method has no effect.
Here’s an example of how to add an element to a Set in Java:
import java.util.HashSet;
import java.util.Set;
public class Example {
public static void main(String[] args) {
// create a set
Set<String> mySet = new HashSet<>();
// add some elements to the set
mySet.add("apple");
mySet.add("banana");
mySet.add("orange");
// add a new element to the set
mySet.add("pear");
// print out the contents of the set
System.out.println("Set: " + mySet);
}
}
In this example, we create a Set called "mySet" using the HashSet class, and add some strings to it using the "add" method. We then add a new string, "pear", to the Set using the "add" method. Finally, we print out the contents of the Set using the "println" method.
The output of this program would be:
Set: [orange, apple, banana, pear]
As you can see, the Set now contains the element "pear", which was added using the "add" method.