020-002-010

Managing Unique Elements with HashSet

Easy

Problem Description

Managing Unique Elements with HashSet

In this problem: You will create a program using HashSet<String> to manage a name list, confirming that duplicate additions are ignored, while checking element existence, getting size, and displaying all elements.

Learning Objective: Understand basic operations of HashSet (add, search, size retrieval) as part of the collection framework

Overview

HashSet is a collection that does not allow duplicates. Even if the same element is added multiple times, only one instance is kept. Its key feature is fast element lookup (O(1) average).

Specifications

  • Create a HashSet<String>
  • Add "Alice", "Bob", "Alice", "Charlie" in order ("Alice" is added twice)
  • Print "Size: " + set size
  • Print "Contains Alice: " + result of contains("Alice")
  • Print "Contains Dave: " + result of contains("Dave")
  • Print "--- All names ---"
  • Convert to TreeSet and print elements in sorted order, one per line

Output Format

Size: 3
Contains Alice: true
Contains Dave: false
--- All names ---
Alice
Bob
Charlie

Ready to Try Running Code?

Log in to access the code editor and execute your solutions for this problem.

Don't have an account?

Sign Up