Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Java HashSet add() Method

Java HashSet add() Method

Java HashSet Java HashSet

add() The method is HashSet one of the most commonly used methods in the class; its role is to add an element to the set.

Method Syntax

public

boolean

add

(

E e

)

Parameter Description

Return Value

Basic Example

Example

import

java.util.HashSet

;

public

class

HashSetExample

{

   

public

static

void

main

(

String

[

]

args

)

{

       

// Create a HashSet

        HashSet

<
String
fruits
=
new
HashSet
<>
(
)

;

       

       

// Add elements

       

boolean

isAdded1

=

fruits.

add

(

"Apple"

)

;

 

// Returns true

       

boolean

isAdded2

=

fruits.

add

(

"Banana"

)

;

// Returns true

       

boolean

isAdded3

=

fruits.

add

(

"Apple"

)

;

 

// Returns false because Apple already exists

       

       

System

.

out

.

println

(

fruits

)

;

// Output: [Apple, Banana]

       

System

.

out

.

println

(

"First addition of Apple: "

isAdded1

)

;

       

System

.

out

.

println

(

"First addition of Banana: "

isAdded2

)

;

       

System

.

out

.

println

(

"Second addition of Apple: "

isAdded3

)

;

   

}

}


Underlying Principle of the add() Method

Understand add() Understanding how the method works helps us use it better HashSet.

Process of Adding an Element

  1. Calculate the hash value: first calculate the hash value of the element to be added hashCode()
  2. Determine the storage location: determine the storage location of the element in the hash table based on the hash value
  3. Check whether it already exists:
  4. If the position is empty, store the element directly
  5. If the position is not empty, call equals() method to compare whether elements are equal
  6. - If the position is empty, store the element directly - If the position is not empty, call the `equals()` method to compare whether elements are equal
    1. Decide whether to add:
    2. If the elements are the same, do not add and return false
    3. If the elements are different (hash collision), they may be stored at different positions in the same bucket
    4. - If the elements are the same, do not add and return `false` - If the elements are different (hash collision), they may be stored at different positions in the same bucket

      Important Notes


      Time Complexity of the add() Method

      HashSet 's add() The time complexity of the method in the ideal case (no hash collisions) is O(1). This means that no matter how many elements are in the set, the time to add a new element is roughly the same.

      However, in extreme cases (all elements hash to the same position), the time complexity degrades to O(n), because it needs to traverse the linked list or red-black tree to check whether the element already exists.


      Practical Applications of the add() Method

      Example 1: Deduplication

      Example

      import

      java.util.HashSet

      ;

      public

      class

      DeduplicationExample

      {

         

      public

      static

      void

      main

      (

      String

      [

      ]

      args

      )

      {

             

      String

      [

      ]

      names

      =

      {

      "Alice"

      ,

      "Bob"

      ,

      "Alice"

      ,

      "Charlie"

      ,

      "Bob"

      }

      ;

             

              HashSet

      <
      String
      uniqueNames
      =
      new
      HashSet
      <>
      (
      )

      ;

             

      for

      (

      String

      name

      :

      names

      )

      {

                  uniqueNames.

      add

      (

      name

      )

      ;

             

      }

             

             

      System

      .

      out

      .

      println

      (

      uniqueNames

      )

      ;

      // Output: [Alice, Bob, Charlie]

         

      }

      }

      Example 2: Counting the Number of Unique Elements

      Example

      import

      java.util.HashSet

      ;

      public

      class

      UniqueCounter

      {

         

      public

      static

      void

      main

      (

      String

      [

      ]

      args

      )

      {

             

      int

      [

      ]

      numbers

      =

      {

      1

      ,

      2

      ,

      3

      ,

      2

      ,

      4

      ,

      1

      ,

      5

      }

      ;

             

              HashSet

      <
      Integer
      uniqueNumbers
      =
      new
      HashSet
      <>
      (
      )

      ;

             

      for

      (

      int

      num

      :

      numbers

      )

      {

                  uniqueNumbers.

      add

      (

      num

      )

      ;

             

      }

             

             

      System

      .

      out

      .

      println

      (

      "Number of unique elements: "

      uniqueNumbers.

      size

      (

      )

      )

      ;

      // Output: 5

         

      }

      }


      Frequently Asked Questions

      1. Why does the add() method return false when adding a duplicate element?

      Because HashSet The design principle of does not allow duplicate elements. When trying to add an element that already exists, the set does not change and the method returns false to indicate that the add operation did not actually occur.

      2. How to determine whether two elements are "the same"?

      HashSet Use the following rules to determine whether two elements are the same:

      1. First compare hashCode() Return Value
      2. If the hash values are the same, then call equals() method to compare

      Only when the two elements' hashCode() are the sameand equals() Return true is it considered the same element.

      3. Can you add a null value?

      Yes,HashSet allows adding null values, but only once (because sets do not allow duplicates).

      Example

      HashSet

      <
      String
      set
      =
      new
      HashSet
      <>
      (
      )

      ;

      set.

      add

      (

      null

      )

      ;

       

      // Returns true

      set.

      add

      (

      null

      )

      ;

       

      // Returns false


      Summary

      By mastering add() With the usage and principles of the method, you can make better use of HashSet to solve various programming problems.

      Java HashSet Java HashSet