Java HashSet remove() Method
HashSet.remove()is an important method in the Java Collections FrameworkHashSetclass provides an important method, used to remove the specified element from the set. This method is inherited fromjava.util.AbstractCollectionclass, and inHashSetimplements the concrete functionality.
Method Syntax
Example
Method Parameters
Object o: The element to be removed from the set- Can be an object of any type
- If the element does not exist in the set, no operation is performed
Return Value
- Returns
booleanType:true: If the set contained the specified element and it was successfully removedfalse: If the set did not contain the specified element
Method Characteristics
Hash table-based implementation
HashSetInternally uses a hash table to store elements,remove()the method quickly locates and removes the element by computing the element's hash code, with an average time complexity of O(1).
Element uniqueness
HashSetDuplicate elements are not allowed, soremove()the method will only remove the first matching element (if multiple identical elements existed, in factHashSetduplicate elements are not stored).
Compatibility with null
HashSetAllows storingnullvalues, so you can also useremove()method to removenullelements.
Usage Examples
Basic Usage
Example
public class HashSetRemoveExample {
public static void main(String[] args) {
// Create a HashSet
HashSet<String> fruits = new HashSet<>();
// Add elements
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Orange");
fruits.add(null); // Add a null element
System.out.println("Original set: " + fruits);
// Output: Original set: [null, Apple, Orange, Banana]
// Remove an element
boolean isRemoved = fruits.remove("Banana");
System.out.println("Remove 'Banana': " + isRemoved);
// Output: Remove 'Banana': true
// Try to remove a non-existent element
isRemoved = fruits.remove("Grape");
System.out.println("Remove 'Grape': " + isRemoved);
// Output: Remove 'Grape': false
// Remove the null element
isRemoved = fruits.remove(null);
System.out.println("Remove null: " + isRemoved);
// Output: Remove null: true
System.out.println("Modified set: " + fruits);
// Output: Modified set: [Apple, Orange]
}
}
Using Custom Objects
When using custom objects, you need to correctly overrideequals()andhashCode()methods, otherwiseremove()the method may not work correctly:
Example
class Student {
private int id;
private String name;
public Student(int id, String name) {
this.id = id;
this.name = name;
}
// Must override equals and hashCode methods
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o;
return id == student.id && name.equals(student.name);
}
@Override
public int hashCode() {
return 31 * id + name.hashCode();
}
@Override
public String toString() {
return "Student{" + "id=" + id + ", name='" + name + '\'' + '}';
}
}
public class CustomObjectExample {
public static void main(String[] args) {
HashSet<Student> students = new HashSet<>();
students.add(new Student(1, "Alice"));
students.add(new Student(2, "Bob"));
System.out.println("Original set: " + students);
// Try to remove a student
boolean removed = students.remove(new Student(1, "Alice"));
System.out.println("Remove Alice: " + removed); // Output: Remove Alice: true
System.out.println("Modified set: " + students);
}
}
Important Notes
Concurrent Modification
HashSetis not thread-safe. If, when iterating the collection (e.g., using a for-each loop), you try to callremove()method, it will throwConcurrentModificationException. If you need to remove while iterating, you should use the iterator'sremove()method.
Performance Considerations
AlthoughHashSet.remove()average time complexity is O(1), in cases of severe hash collisions, performance degrades to O(n). Therefore, a goodhashCode()implementation is important for maintaining high performance.
Difference from Iterator remove()
Directly callingHashSet.remove()and calling via the iteratorremove()difference:
HashSet.remove(): Removes based on element valueIterator.remove(): Removes the element currently being iterated
Summary
HashSet.remove()method is an operationHashSetone of the basic methods of the collection, providing efficient element removal. When using, note:
- Correctly implement
equals()andhashCode()methods (for custom objects) - Handle concurrent modification issues
- Understand the operation result represented by the return value
Through proper useremove()of the method, you can effectively manageHashSetelements in the collection.
Java HashSet