WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Java Collections · Basic · question 5 of 100

How do you add an element to a Set in Java?

📕 Buy this interview preparation book: 100 Java Collections questions & answers — PDF + EPUB for $5

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.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Java Collections interview — then scores it.
📞 Practice Java Collections — free 15 min
📕 Buy this interview preparation book: 100 Java Collections questions & answers — PDF + EPUB for $5

All 100 Java Collections questions · All topics