Saturday, October 11, 2025
HomeLanguagesJavaBitSet clone() Method in Java with Examples

BitSet clone() Method in Java with Examples

The clone() Method Java.util.BitSet class is used to create a copy of an existing BitSet. The new BitSet is exactly equal to the existing one and is a mere copy of the previous BitSet.

Syntax:

Bit_Set.clone()

Parameters: The method does not take any parameters.

Return Value: The method just returns another copy of the existing BitSet.

Below programs illustrate the working of BitSet clone() method in Java.
Program 1:




// Java code to illustrate clone()
import java.util.*;
  
public class BitSet_Demo {
    public static void main(String args[])
    {
        // Creating an empty BitSet
        BitSet init_bitset = new BitSet();
  
        // Use set() method to add elements into the Set
        init_bitset.set(10);
        init_bitset.set(20);
        init_bitset.set(30);
        init_bitset.set(40);
        init_bitset.set(50);
  
        // Displaying the BitSet
        System.out.println("Initial BitSet: " + init_bitset);
  
        // Creating a new cloned set
        BitSet cloned_set = new BitSet();
  
        // Cloning the set using clone() method
        cloned_set = (BitSet)init_bitset.clone();
  
        // Displaying the new Set after Cloning
        System.out.println("The new BitSet: " + cloned_set);
    }
}


Output:

Initial BitSet: {10, 20, 30, 40, 50}
The new BitSet: {10, 20, 30, 40, 50}

Program 2:




// Java code to illustrate clone()
import java.util.*;
  
public class BitSet_Demo {
    public static void main(String args[])
    {
        // Creating an empty BitSet
        BitSet init_bitset = new BitSet();
  
        // Use set() method to add elements into the Set
        init_bitset.set(40);
        init_bitset.set(25);
        init_bitset.set(80);
        init_bitset.set(95);
        init_bitset.set(5);
  
        // Displaying the BitSet
        System.out.println("Initial BitSet: " + init_bitset);
  
        // Creating a new cloned set
        BitSet cloned_set = new BitSet();
  
        // Cloning the set using clone() method
        cloned_set = (BitSet)init_bitset.clone();
  
        // Displaying the new Set after Cloning
        System.out.println("The new BitSet: " + cloned_set);
    }
}


Output:

Initial BitSet: {5, 25, 40, 80, 95}
The new BitSet: {5, 25, 40, 80, 95}
RELATED ARTICLES

Most Popular

Dominic
32350 POSTS0 COMMENTS
Milvus
87 POSTS0 COMMENTS
Nango Kala
6720 POSTS0 COMMENTS
Nicole Veronica
11882 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11941 POSTS0 COMMENTS
Shaida Kate Naidoo
6839 POSTS0 COMMENTS
Ted Musemwa
7101 POSTS0 COMMENTS
Thapelo Manthata
6794 POSTS0 COMMENTS
Umr Jansen
6794 POSTS0 COMMENTS