HashSet clone() Method in Java

Published by user on

The clone() method of HashSet returns a shallow copy of this HashSet instance. It overrides the clone() method of Object.

Syntax

Object clone()

Parameters

It does not take any parameter

Return Value

it returns a shallow copy of this HashSet instance.

Program 1

import java.util.HashSet;

public class HashSetCloneExample {

        public static void main(String[] args) {

                HashSet set = new HashSet();
                set.add(10);
                set.add(20);
                set.add(30);
                set.add(40);
                set.add(50);

                System.out.println("Set elements : " + set);
                Object clonedSet = set.clone();
                System.out.println("Cloned set elements : " + clonedSet);
        }
}

Output

Set elements : [50, 20, 40, 10, 30]
Cloned set elements : [40, 50, 10, 20, 30]
Categories: Java

0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *