📜  Java中的 TreeMap clone() 方法及示例(1)

📅  最后修改于: 2023-12-03 15:01:57.765000             🧑  作者: Mango

Java中的 TreeMap clone() 方法及示例

TreeMap是Java中一个有序的映射集合,它基于红黑树实现。与HashMap不同,TreeMap能保证根据键的自然顺序或Comparator的顺序进行排序。在TreeMap中,clone()方法用于创建并返回一个与原始TreeMap相同键值对的映射,它与原始映射相互独立,即它们的更改不会互相影响。

clone()方法的源码如下:

public Object clone() {
    TreeMap<K,V> clone;
    try {
        @SuppressWarnings("unchecked")
        clone = (TreeMap<K,V>) super.clone();
    } catch (CloneNotSupportedException e) {
        throw new InternalError(e);
    }

    // Clone the elements
    clone.root = null;
    clone.size = 0;
    clone.modCount = 0;
    clone.entrySet = null;
    clone.navigableKeySet = null;
    clone.descendingMap = null;

    try {
        clone.buildFromSorted(size, entrySet().iterator(), null, null);
    } catch (java.io.IOException cannotHappen) {
    } catch (ClassNotFoundException cannotHappen) {
    }

    return clone;
}

可以看出,clone()方法首先调用父类Object的clone()方法,然后在新的TreeMap对象中克隆原始Map的元素,最后返回新的TreeMap对象。

以下是示例代码,展示了如何使用TreeMap的clone()方法:

import java.util.TreeMap;

public class TreeMapExample {
    public static void main(String[] args) {
        // Create a TreeMap and add some key-value pairs
        TreeMap<String, Integer> treeMap = new TreeMap<>();
        treeMap.put("John", 23);
        treeMap.put("Emily", 21);
        treeMap.put("Derek", 25);

        // Print the original TreeMap
        System.out.println("Original TreeMap: " + treeMap);

        // Create a clone of the original TreeMap
        TreeMap<String, Integer> cloneMap = (TreeMap<String, Integer>) treeMap.clone();

        // Add a new key-value pair to the original TreeMap
        treeMap.put("Anna", 27);

        // Print the original TreeMap after adding a new key-value pair
        System.out.println("Original TreeMap after adding a new key-value pair: " + treeMap);

        // Print the clone of the original TreeMap
        System.out.println("Clone of the original TreeMap: " + cloneMap);
    }
}

输出结果如下:

Original TreeMap: {Derek=25, Emily=21, John=23}
Original TreeMap after adding a new key-value pair: {Anna=27, Derek=25, Emily=21, John=23}
Clone of the original TreeMap: {Derek=25, Emily=21, John=23}

可以看到,当原始TreeMap添加新的键值对后,克隆Map并没有被影响,它们按照之前的状态保持不变。