?? treemap.java
字號:
/* * @(#)TreeMap.java 1.50 06/10/10 * * Copyright 1990-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License version * 2 only, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License version 2 for more details (a copy is * included at /legal/license.txt). * * You should have received a copy of the GNU General Public License * version 2 along with this work; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA * * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa * Clara, CA 95054 or visit www.sun.com if you need additional * information or have any questions. * */package java.util;/** * Red-Black tree based implementation of the <tt>SortedMap</tt> interface. * This class guarantees that the map will be in ascending key order, sorted * according to the <i>natural order</i> for the key's class (see * <tt>Comparable</tt>), or by the comparator provided at creation time, * depending on which constructor is used.<p> * * This implementation provides guaranteed log(n) time cost for the * <tt>containsKey</tt>, <tt>get</tt>, <tt>put</tt> and <tt>remove</tt> * operations. Algorithms are adaptations of those in Cormen, Leiserson, and * Rivest's <I>Introduction to Algorithms</I>.<p> * * Note that the ordering maintained by a sorted map (whether or not an * explicit comparator is provided) must be <i>consistent with equals</i> if * this sorted map is to correctly implement the <tt>Map</tt> interface. (See * <tt>Comparable</tt> or <tt>Comparator</tt> for a precise definition of * <i>consistent with equals</i>.) This is so because the <tt>Map</tt> * interface is defined in terms of the equals operation, but a map performs * all key comparisons using its <tt>compareTo</tt> (or <tt>compare</tt>) * method, so two keys that are deemed equal by this method are, from the * standpoint of the sorted map, equal. The behavior of a sorted map * <i>is</i> well-defined even if its ordering is inconsistent with equals; it * just fails to obey the general contract of the <tt>Map</tt> interface.<p> * * <b>Note that this implementation is not synchronized.</b> If multiple * threads access a map concurrently, and at least one of the threads modifies * the map structurally, it <i>must</i> be synchronized externally. (A * structural modification is any operation that adds or deletes one or more * mappings; merely changing the value associated with an existing key is not * a structural modification.) This is typically accomplished by * synchronizing on some object that naturally encapsulates the map. If no * such object exists, the map should be "wrapped" using the * <tt>Collections.synchronizedMap</tt> method. This is best done at creation * time, to prevent accidental unsynchronized access to the map: * <pre> * Map m = Collections.synchronizedMap(new TreeMap(...)); * </pre><p> * * The iterators returned by all of this class's "collection view methods" are * <i>fail-fast</i>: if the map is structurally modified at any time after the * iterator is created, in any way except through the iterator's own * <tt>remove</tt> or <tt>add</tt> methods, the iterator throws a * <tt>ConcurrentModificationException</tt>. Thus, in the face of concurrent * modification, the iterator fails quickly and cleanly, rather than risking * arbitrary, non-deterministic behavior at an undetermined time in the * future. * * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed * as it is, generally speaking, impossible to make any hard guarantees in the * presence of unsynchronized concurrent modification. Fail-fast iterators * throw <tt>ConcurrentModificationException</tt> on a best-effort basis. * Therefore, it would be wrong to write a program that depended on this * exception for its correctness: <i>the fail-fast behavior of iterators * should be used only to detect bugs.</i><p> * * This class is a member of the * <a href="{@docRoot}/../guide/collections/index.html"> * Java Collections Framework</a>. * * @author Josh Bloch and Doug Lea * @version 1.43, 02/02/00 * @see Map * @see HashMap * @see Hashtable * @see Comparable * @see Comparator * @see Collection * @see Collections#synchronizedMap(Map) * @since 1.2 */public class TreeMap extends AbstractMap implements SortedMap, Cloneable, java.io.Serializable{ /** * The Comparator used to maintain order in this TreeMap, or * null if this TreeMap uses its elements natural ordering. * * @serial */ private Comparator comparator = null; private transient Entry root = null; /** * The number of entries in the tree */ private transient int size = 0; /** * The number of structural modifications to the tree. */ private transient int modCount = 0; private void incrementSize() { modCount++; size++; } private void decrementSize() { modCount++; size--; } /** * Constructs a new, empty map, sorted according to the keys' natural * order. All keys inserted into the map must implement the * <tt>Comparable</tt> interface. Furthermore, all such keys must be * <i>mutually comparable</i>: <tt>k1.compareTo(k2)</tt> must not throw a * ClassCastException for any elements <tt>k1</tt> and <tt>k2</tt> in the * map. If the user attempts to put a key into the map that violates this * constraint (for example, the user attempts to put a string key into a * map whose keys are integers), the <tt>put(Object key, Object * value)</tt> call will throw a <tt>ClassCastException</tt>. * * @see Comparable */ public TreeMap() { } /** * Constructs a new, empty map, sorted according to the given comparator. * All keys inserted into the map must be <i>mutually comparable</i> by * the given comparator: <tt>comparator.compare(k1, k2)</tt> must not * throw a <tt>ClassCastException</tt> for any keys <tt>k1</tt> and * <tt>k2</tt> in the map. If the user attempts to put a key into the * map that violates this constraint, the <tt>put(Object key, Object * value)</tt> call will throw a <tt>ClassCastException</tt>. * * @param c the comparator that will be used to sort this map. A * <tt>null</tt> value indicates that the keys' <i>natural * ordering</i> should be used. */ public TreeMap(Comparator c) { this.comparator = c; } /** * Constructs a new map containing the same mappings as the given map, * sorted according to the keys' <i>natural order</i>. All keys inserted * into the new map must implement the <tt>Comparable</tt> interface. * Furthermore, all such keys must be <i>mutually comparable</i>: * <tt>k1.compareTo(k2)</tt> must not throw a <tt>ClassCastException</tt> * for any elements <tt>k1</tt> and <tt>k2</tt> in the map. This method * runs in n*log(n) time. * * @param m the map whose mappings are to be placed in this map. * @throws ClassCastException the keys in t are not Comparable, or * are not mutually comparable. * @throws NullPointerException if the specified map is null. */ public TreeMap(Map m) { putAll(m); } /** * Constructs a new map containing the same mappings as the given * <tt>SortedMap</tt>, sorted according to the same ordering. This method * runs in linear time. * * @param m the sorted map whose mappings are to be placed in this map, * and whose comparator is to be used to sort this map. * @throws NullPointerException if the specified sorted map is null. */ public TreeMap(SortedMap m) { comparator = m.comparator(); try { buildFromSorted(m.size(), m.entrySet().iterator(), null, null); } catch (java.io.IOException cannotHappen) { } catch (ClassNotFoundException cannotHappen) { } } // Query Operations /** * Returns the number of key-value mappings in this map. * * @return the number of key-value mappings in this map. */ public int size() { return size; } /** * Returns <tt>true</tt> if this map contains a mapping for the specified * key. * * @param key key whose presence in this map is to be tested. * * @return <tt>true</tt> if this map contains a mapping for the * specified key. * @throws ClassCastException if the key cannot be compared with the keys * currently in the map. * @throws NullPointerException key is <tt>null</tt> and this map uses * natural ordering, or its comparator does not tolerate * <tt>null</tt> keys. */ public boolean containsKey(Object key) { return getEntry(key) != null; } /** * Returns <tt>true</tt> if this map maps one or more keys to the * specified value. More formally, returns <tt>true</tt> if and only if * this map contains at least one mapping to a value <tt>v</tt> such * that <tt>(value==null ? v==null : value.equals(v))</tt>. This * operation will probably require time linear in the Map size for most * implementations of Map. * * @param value value whose presence in this Map is to be tested. * @return <tt>true</tt> if a mapping to <tt>value</tt> exists; * <tt>false</tt> otherwise. * @since 1.2 */ public boolean containsValue(Object value) { return (root==null ? false : (value==null ? valueSearchNull(root) : valueSearchNonNull(root, value))); } private boolean valueSearchNull(Entry n) { if (n.value == null) return true; // Check left and right subtrees for value return (n.left != null && valueSearchNull(n.left)) || (n.right != null && valueSearchNull(n.right)); } private boolean valueSearchNonNull(Entry n, Object value) { // Check this node for the value if (value.equals(n.value)) return true; // Check left and right subtrees for value return (n.left != null && valueSearchNonNull(n.left, value)) || (n.right != null && valueSearchNonNull(n.right, value)); } /** * Returns the value to which this map maps the specified key. Returns * <tt>null</tt> if the map contains no mapping for this key. A return * value of <tt>null</tt> does not <i>necessarily</i> indicate that the * map contains no mapping for the key; it's also possible that the map * explicitly maps the key to <tt>null</tt>. The <tt>containsKey</tt> * operation may be used to distinguish these two cases. * * @param key key whose associated value is to be returned. * @return the value to which this map maps the specified key, or * <tt>null</tt> if the map contains no mapping for the key. * @throws ClassCastException key cannot be compared with the keys * currently in the map. * @throws NullPointerException key is <tt>null</tt> and this map uses * natural ordering, or its comparator does not tolerate * <tt>null</tt> keys. * * @see #containsKey(Object) */ public Object get(Object key) { Entry p = getEntry(key); return (p==null ? null : p.value); } /** * Returns the comparator used to order this map, or <tt>null</tt> if this * map uses its keys' natural order. * * @return the comparator associated with this sorted map, or * <tt>null</tt> if it uses its keys' natural sort method. */ public Comparator comparator() { return comparator; } /** * Returns the first (lowest) key currently in this sorted map. * * @return the first (lowest) key currently in this sorted map. * @throws NoSuchElementException Map is empty. */ public Object firstKey() { return key(firstEntry()); } /** * Returns the last (highest) key currently in this sorted map. * * @return the last (highest) key currently in this sorted map. * @throws NoSuchElementException Map is empty. */ public Object lastKey() { return key(lastEntry()); } /** * Copies all of the mappings from the specified map to this map. These * mappings replace any mappings that this map had for any of the keys * currently in the specified map. * * @param map mappings to be stored in this map. * @throws ClassCastException class of a key or value in the specified * map prevents it from being stored in this map. * * @throws NullPointerException if the given map is <tt>null</tt> or * this map does not permit <tt>null</tt> keys and a * key in the specified map is <tt>null</tt>. */ public void putAll(Map map) { int mapSize = map.size(); if (size==0 && mapSize!=0 && map instanceof SortedMap) { Comparator c = ((SortedMap)map).comparator(); if (c == comparator || (c != null && c.equals(comparator))) { ++modCount; try { buildFromSorted(mapSize, map.entrySet().iterator(), null, null); } catch (java.io.IOException cannotHappen) { } catch (ClassNotFoundException cannotHappen) { } return; } } super.putAll(map); } /** * Returns this map's entry for the given key, or <tt>null</tt> if the map * does not contain an entry for the key. * * @return this map's entry for the given key, or <tt>null</tt> if the map * does not contain an entry for the key. * @throws ClassCastException if the key cannot be compared with the keys * currently in the map. * @throws NullPointerException key is <tt>null</tt> and this map uses * natural order, or its comparator does not tolerate * * <tt>null</tt> keys. */ private Entry getEntry(Object key) { Entry p = root; while (p != null) { int cmp = compare(key,p.key); if (cmp == 0) return p; else if (cmp < 0) p = p.left; else p = p.right; } return null; } /** * Gets the entry corresponding to the specified key; if no such entry * exists, returns the entry for the least key greater than the specified * key; if no such entry exists (i.e., the greatest key in the Tree is less * than the specified key), returns <tt>null</tt>. */ private Entry getCeilEntry(Object key) { Entry p = root; if (p==null) return null; while (true) { int cmp = compare(key, p.key); if (cmp == 0) { return p; } else if (cmp < 0) { if (p.left != null) p = p.left; else return p; } else { if (p.right != null) { p = p.right; } else { Entry parent = p.parent; Entry ch = p; while (parent != null && ch == parent.right) { ch = parent; parent = parent.parent; } return parent; } } } } /** * Returns the entry for the greatest key less than the specified key; if * no such entry exists (i.e., the least key in the Tree is greater than * the specified key), returns <tt>null</tt>.
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -