Java教程

Java HashSet clone()

Java HashSet类的 clone()方法用于返回指定HashSet的浅表副本。

语法

以下是 clone()方法的声明:
public Object clone()

参数

此方法不接受任何参数。

返回

clone()方法返回此HashSet的浅表副本。

异常

NA

兼容版本

Java 1.2及更高版本

示例1

import java.util.*;
public class HashSetCloneExample1 {
    public static void main(String[] args) {
        HashSet<String> set = new HashSet<String>();
        set.add("lidihuo");
        set.add("Google");
        set.add("Hindi100");
        set.add("101");
        set.add("Facebook");
        System.out.println("HashSet elements: " + set);
        HashSet<String> clonedSet = new HashSet<String>();
        clonedSet = (HashSet)set.clone();
        System.out.println("The new clone set elements: " + clonedSet);
    }
}
输出:
HashSet elements: [Google, 101, Hindi100, lidihuo, Facebook]
The new clone set elements: [Google, 101, lidihuo, Facebook, Hindi100]

示例2

import java.util.*;
public class HashSetCloneExample2 {
    public static void main(String[] args) {
        HashSet<Integer> hset = new HashSet<Integer>();
        hset.add(121);
        hset.add(111);
        hset.add(151);
        System.out.println("Hash set Elements: "+ hset);
        HashSet<Integer> clonedSet = new HashSet<Integer>();
        clonedSet = (HashSet)hset.clone();
        System.out.println("The new clone set elements: " + clonedSet);
    }
}
输出:
Hash set Elements: [151, 121, 111]
The new clone set elements: [121, 151, 111]

示例3

import java.util.*;
public class HashSetCloneExample3 {
    public static void main(String[] args) {
        HashSet<String> hset1 = new HashSet<>();
        hset1.add("JTP");
        hset1.add("SSSIT");
        hset1.add("DFC");
        System.out.println("Elements of the hset1:");
        for(String temp:hset1)
            {
            System.out.println(temp);
        }
        HashSet<String> hset2 = new HashSet<>();
        hset2 =(HashSet)hset1.clone();
        System.out.println("Elements of the hset2 after clone() operation:");
        for(String temp:hset2)
            {
            System.out.println(temp);
        }
    }
}
输出:
Elements of the hset1:
DFC
SSSIT
JTP
Elements of the hset2 after clone() operation:
DFC
SSSIT
JTP

昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4