克隆HashMap
的程序。我们将使用HashMap
类的以下方法来执行克隆。
public Object clone()
:返回此HashMap
实例的浅表副本:未克隆键和值本身。
示例
import java.util.HashMap;
class HashMapExample{
public static void main(String args[]) {
// Create a HashMap
HashMap<Integer, String> hmap = new HashMap<Integer, String>();
// Adding few elements
hmap.put(11, "Jack");
hmap.put(22, "Rock");
hmap.put(33, "Rick");
hmap.put(44, "Smith");
hmap.put(55, "Will");
System.out.println("HashMap contains: "+hmap);
// Creating a new HashMap
HashMap<Integer, String> hmap2 = new HashMap<Integer, String>();
// cloning first HashMap in the second one
hmap2=(HashMap)hmap.clone();
System.out.println("Cloned Map contains: "+hmap2);
}
}
输出:
HashMap contains: {33=Rick, 55=Will, 22=Rock, 11=Jack, 44=Smith}
Cloned Map contains: {33=Rick, 55=Will, 22=Rock, 11=Jack, 44=Smith}