Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
I am relatively new to Java, and often find that I need to sort a Map on the values. Since the values are not unique, I find myself converting the keySet into an array, and sorting that array through array sort with a custom comparator that sorts on the value associated with the key. Is there an easier way?
I may be teaching a "Java crash-course" soon. While it is probably safe to assume that the audience members will know Big-O notation, it is probably not safe to assume that they will know what the order of the various operations on various collection implementations is. I could take time to generate a summary matrix myself, but if it's already out there in the public domain somewhere, I'd sur...
Description | A Java program to read a text file and print each of the unique words in alphabetical order together with the number of times the word occurs in the text. The program should declare a variable of type Map<String, Integer> to store the words and corresponding frequency of occurrence. Which concrete type, though? TreeMap<String, Number> or HashMap<String, Number>...
Does MATLAB have any support for hash tables? Some background I am working on a problem in Matlab that requires a scale-space representation of an image. To do this I create a 2-D Gaussian filter with variance sigma*s^k for k in some range., and then I use each one in turn to filter the image. Now, I want some sort of mapping from k to the filtered image. If k were always an integer, I'd ...
I have a Map in java that has strings for both . Data is like following <"question1", "1">, <"question9", "1">, <"question2", "4">, <"question5", "2"> I want to sort the map based on its Key's. So In the end I will have question1, question2, question3....an so on. Eventually I am trying to get two strings out of this Map. First String: Questions ( in order 1 ..10) and Second S...
How to move a particular HashMap entry to Last position? For Example, I have HashMap values like this: HashMap<String,Integer> map = new HashMap<String,Integer>(); map= {Not-Specified 1, test 2, testtest 3}; "Not-Specified" may come in any position. it may come first or in the middle of the map. But i want to move the "Not-Specified" to the last position. How can I do that? th...
I was wandering if there is a class out there that implements both Map and List interfaces in Java. I have a data structure that is primarily a Map. I map strings (IDs) to Images. But in a specific part of my code i need to present the user with all the available IDed Images. The only way to do that so far is to write this : for (String id : myMap.keySet()) { // get the image like this "...
I have a simple java method that returns colors based on the HSB value converted from an RGB. It works (needs some tweaking), but I use a series of else if and nested if statements to return the data I want. I had heard that HashMaps and String Factories were better, but I couldn't see how these worked with ranged data. Is there a better solution that works with ranged data like this? Snippet:...
I have a general question on your opinion about my "technique". There are 2 textfiles (file_1 and file_2) that need to be compared to each other. Both are very huge (3-4 gigabytes, from 30,000,000 to 45,000,000 lines each). My idea is to read several lines (as many as possible) of file_1 to the memory, then compare those to all lines of file_2. If there's a match, the lines from both files th...
Let's say that I have two arrays (in Java), int[] numbers; and int[] colors; Each ith element of numbers corresponds to its ith element in colors. Ex, numbers = {4,2,1} colors = {0x11, 0x24, 0x01}; Means that number 4 is color 0x11, number 2 is 0x24, etc. I want to sort the numbers array, but then still have it so each element matches up with its pair in colors. Ex. numbers = {1,2,4}; ...
Map m1 = new HashMap(); m1.put("map", "HashMap"); m1.put("schildt", "java2"); m1.put("mathew", "Hyden"); m1.put("schildt", "java2s"); print(m1.keySet()); print(m1.values()); SortedMap sm = new TreeMap(); sm.put("map", "TreeMap"); sm.put("schildt", "java2"); sm.put("mathew", "Hyden"); sm.put("schildt", "java2s"); print(sm.keySet()); pri...
This is a nasty one for me... I'm a PHP guy working in Java on a JSP project. I know how to do what I'm attempting through too much code and a complete lack of finesse. I'd prefer to do it RIGHT. :) Here is the situation: I'm writing a small display to show customers what days they can water their lawns based on their watering group (ABCDE) and what time of year it is. Our seasons look li...
how we will be able to sort a hashmap i want so sort in the basis of a value in array list... thanx in advance..............
I need to iterate through SortedMap's entry set (which is a SortedSet) backwards. The code I'm writing is extremely performance-sensitive, as it's going to be called from many places thousands times per second, maybe more. Any advice on doing it the fastest way?
Let's say that I need to make a mapping from String to an integer. The integers are unique and form a continuous range starting from 0. That is: Hello -> 0 World -> 1 Foo -> 2 Bar -> 3 Spam -> 4 Eggs -> 5 etc. There are at least two straightforward ways to do it. With a hashmap: HashMap<String, Integer> map = ... int integer = map.get(string); // Plus maybe nul...
I want to know whether a particular key is present in a HashMap, so i am using containsKey(key) method. But it is case sensitive ie it does not returns true if there is a key with Name and i am searching for name. So is there any way i can know without bothering the case of the key? thanks
I am looking for a pre-built Java data structure with the following characteristics: It should look something like an ArrayList but should allow indexing via double-precision rather than integers. Note that this means that it's likely that you'll see indicies that don't line up with the original data points (i.e., asking for the value that corresponds to key "1.5"). EDIT: For clarity, based...
This is very similar to another question (Functional Data Structures in Java) but the answers there are not particularly useful. I need to use immutable versions of the standard Java collections (e.g. HashMap / TreeMap / ArrayList / LinkedList / HashSet / TreeSet). By "immutable" I mean immutable in the functional sense (e.g. purely functional data structures), where updating operations on the...
I have a HashMap with millions of entries. Need to retrieve all entries whose keys match a specific set of criteria (in this case, each key is an object with two integer properties; I need to retrieve all keys where each of these integers fall within a specified range). What is the fastest, most efficient way to iterate through all such keys? UPDATE: In this particular case, though I didn't ...
I'm looking for a class in java that has key-value association, but without using hashes. Here is what I'm currently doing: Add values to a Hashtable Get an iterator for the Hashtable.entrySet(). Iterate through all values and: Get a Map.Entry for the iterator Create an object of type Module (a custom class) based on the value. Add the class to a JPanel; Show the panel. The problem with ...
I started learning Java. When do use Hashmap over Treemap?
   /*
    * Copyright 1997-2008 Sun Microsystems, Inc.  All Rights Reserved.
    * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
    *
    * This code 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.  Sun designates this
    * particular file as subject to the "Classpath" exception as provided
    * by Sun in the LICENSE file that accompanied this code.
   *
   * This code 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 in the LICENSE file that
   * accompanied this code).
   *
   * 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 USA or visit www.sun.com if you need additional information or
   * have any questions.
   */
  
  package java.util;

A Red-Black tree based NavigableMap implementation. The map is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used.

This implementation provides guaranteed log(n) time cost for the containsKey, get, put and remove operations. Algorithms are adaptations of those in Cormen, Leiserson, and Rivest's Introduction to Algorithms.

Note that the ordering maintained by a sorted map (whether or not an explicit comparator is provided) must be consistent with equals if this sorted map is to correctly implement the Map interface. (See Comparable or Comparator for a precise definition of consistent with equals.) This is so because the Map interface is defined in terms of the equals operation, but a map performs all key comparisons using its compareTo (or compare) 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 is well-defined even if its ordering is inconsistent with equals; it just fails to obey the general contract of the Map interface.

Note that this implementation is not synchronized. If multiple threads access a map concurrently, and at least one of the threads modifies the map structurally, it must 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 Collections.synchronizedSortedMap method. This is best done at creation time, to prevent accidental unsynchronized access to the map:

   SortedMap m = Collections.synchronizedSortedMap(new TreeMap(...));

The iterators returned by the iterator method of the collections returned by all of this class's "collection view methods" are fail-fast: if the map is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove method, the iterator will throw a ConcurrentModificationException. 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.

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 ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs.

All Map.Entry pairs returned by methods in this class and its views represent snapshots of mappings at the time they were produced. They do not support the Entry.setValue method. (Note however that it is possible to change mappings in the associated map using put.)

This class is a member of the Java Collections Framework.

Parameters:
<K> the type of keys maintained by this map
<V> the type of mapped values
Author(s):
Josh Bloch and Doug Lea
Since:
1.2
See also:
Map
HashMap
Hashtable
java.lang.Comparable
Comparator
Collection
 
 
 public class TreeMap<K,V>
     extends AbstractMap<K,V>
     implements NavigableMap<K,V>, Cloneablejava.io.Serializable
 {
    
The comparator used to maintain order in this tree map, or null if it uses the natural ordering of its keys.

Serial:
 
     private final Comparator<? super K> comparator;
 
     private transient Entry<K,V> 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;

    
Constructs a new, empty tree map, using the natural ordering of its keys. All keys inserted into the map must implement the java.lang.Comparable interface. Furthermore, all such keys must be mutually comparable: k1.compareTo(k2) must not throw a ClassCastException for any keys k1 and k2 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 put(Object key, Object value) call will throw a ClassCastException.
 
     public TreeMap() {
          = null;
     }

    
Constructs a new, empty tree map, ordered according to the given comparator. All keys inserted into the map must be mutually comparable by the given comparator: comparator.compare(k1, k2) must not throw a ClassCastException for any keys k1 and k2 in the map. If the user attempts to put a key into the map that violates this constraint, the put(Object key, Object value) call will throw a ClassCastException.

Parameters:
comparator the comparator that will be used to order this map. If null, the natural ordering of the keys will be used.
 
     public TreeMap(Comparator<? super K> comparator) {
         this. = comparator;
     }

    
Constructs a new tree map containing the same mappings as the given map, ordered according to the natural ordering of its keys. All keys inserted into the new map must implement the java.lang.Comparable interface. Furthermore, all such keys must be mutually comparable: k1.compareTo(k2) must not throw a ClassCastException for any keys k1 and k2 in the map. This method runs in n*log(n) time.

Parameters:
m the map whose mappings are to be placed in this map
Throws:
java.lang.ClassCastException if the keys in m are not java.lang.Comparable, or are not mutually comparable
java.lang.NullPointerException if the specified map is null
 
     public TreeMap(Map<? extends K, ? extends V> m) {
          = null;
         putAll(m);
     }

    
Constructs a new tree map containing the same mappings and using the same ordering as the specified sorted map. This method runs in linear time.

Parameters:
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:
java.lang.NullPointerException if the specified map is null
 
     public TreeMap(SortedMap<K, ? extends V> m) {
          = m.comparator();
         try {
             buildFromSorted(m.size(), m.entrySet().iterator(), nullnull);
         } catch (java.io.IOException cannotHappen) {
         } catch (ClassNotFoundException cannotHappen) {
         }
     }
 
 
     // Query Operations
 
    
Returns the number of key-value mappings in this map.

Returns:
the number of key-value mappings in this map
 
     public int size() {
         return ;
     }

    
Returns true if this map contains a mapping for the specified key.

Parameters:
key key whose presence in this map is to be tested
Returns:
true if this map contains a mapping for the specified key
Throws:
java.lang.ClassCastException if the specified key cannot be compared with the keys currently in the map
java.lang.NullPointerException if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys
 
     public boolean containsKey(Object key) {
         return getEntry(key) != null;
     }

    
Returns true if this map maps one or more keys to the specified value. More formally, returns true if and only if this map contains at least one mapping to a value v such that (value==null ? v==null : value.equals(v)). This operation will probably require time linear in the map size for most implementations.

Parameters:
value value whose presence in this map is to be tested
Returns:
true if a mapping to value exists; false otherwise
Since:
1.2
 
     public boolean containsValue(Object value) {
         for (Entry<K,V> e = getFirstEntry(); e != nulle = successor(e))
             if (valEquals(valuee.value))
                 return true;
         return false;
     }

    
Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.

More formally, if this map contains a mapping from a key k to a value v such that key compares equal to k according to the map's ordering, then this method returns v; otherwise it returns null. (There can be at most one such mapping.)

A return value of null does not necessarily indicate that the map contains no mapping for the key; it's also possible that the map explicitly maps the key to null. The containsKey operation may be used to distinguish these two cases.

Throws:
java.lang.ClassCastException if the specified key cannot be compared with the keys currently in the map
java.lang.NullPointerException if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys
 
     public V get(Object key) {
         Entry<K,V> p = getEntry(key);
         return (p==null ? null : p.value);
     }
 
     public Comparator<? super K> comparator() {
         return ;
     }

    
 
     public K firstKey() {
         return key(getFirstEntry());
     }

    
 
     public K lastKey() {
         return key(getLastEntry());
     }

    
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.

Parameters:
map mappings to be stored in this map
Throws:
java.lang.ClassCastException if the class of a key or value in the specified map prevents it from being stored in this map
java.lang.NullPointerException if the specified map is null or the specified map contains a null key and this map does not permit null keys
 
     public void putAll(Map<? extends K, ? extends V> map) {
         int mapSize = map.size();
         if (==0 && mapSize!=0 && map instanceof SortedMap) {
             Comparator c = ((SortedMap)map).comparator();
             if (c ==  || (c != null && c.equals())) {
                 ++;
                 try {
                     buildFromSorted(mapSizemap.entrySet().iterator(),
                                     nullnull);
                 } catch (java.io.IOException cannotHappen) {
                 } catch (ClassNotFoundException cannotHappen) {
                 }
                 return;
             }
         }
         super.putAll(map);
     }

    
Returns this map's entry for the given key, or null if the map does not contain an entry for the key.

Returns:
this map's entry for the given key, or null if the map does not contain an entry for the key
Throws:
java.lang.ClassCastException if the specified key cannot be compared with the keys currently in the map
java.lang.NullPointerException if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys
 
     final Entry<K,V> getEntry(Object key) {
         // Offload comparator-based version for sake of performance
         if ( != null)
             return getEntryUsingComparator(key);
         if (key == null)
             throw new NullPointerException();
         Comparable<? super K> k = (Comparable<? super K>) key;
         Entry<K,V> p = ;
         while (p != null) {
             int cmp = k.compareTo(p.key);
             if (cmp < 0)
                 p = p.left;
             else if (cmp > 0)
                 p = p.right;
             else
                 return p;
         }
         return null;
     }

    
Version of getEntry using comparator. Split off from getEntry for performance. (This is not worth doing for most methods, that are less dependent on comparator performance, but is worthwhile here.)
 
     final Entry<K,V> getEntryUsingComparator(Object key) {
         K k = (K) key;
         Comparator<? super K> cpr = ;
         if (cpr != null) {
             Entry<K,V> p = ;
             while (p != null) {
                 int cmp = cpr.compare(kp.key);
                 if (cmp < 0)
                     p = p.left;
                 else if (cmp > 0)
                     p = p.right;
                 else
                     return p;
             }
         }
         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 null.
 
     final Entry<K,V> getCeilingEntry(K key) {
         Entry<K,V> p = ;
         while (p != null) {
             int cmp = compare(keyp.key);
             if (cmp < 0) {
                 if (p.left != null)
                     p = p.left;
                 else
                     return p;
             } else if (cmp > 0) {
                 if (p.right != null) {
                     p = p.right;
                 } else {
                     Entry<K,V> parent = p.parent;
                     Entry<K,V> ch = p;
                     while (parent != null && ch == parent.right) {
                         ch = parent;
                         parent = parent.parent;
                     }
                     return parent;
                 }
             } else
                 return p;
         }
         return null;
     }

    
Gets the entry corresponding to the specified key; if no such entry exists, returns the entry for the greatest key less than the specified key; if no such entry exists, returns null.
 
     final Entry<K,V> getFloorEntry(K key) {
         Entry<K,V> p = ;
         while (p != null) {
             int cmp = compare(keyp.key);
             if (cmp > 0) {
                 if (p.right != null)
                     p = p.right;
                 else
                     return p;
             } else if (cmp < 0) {
                 if (p.left != null) {
                     p = p.left;
                 } else {
                     Entry<K,V> parent = p.parent;
                     Entry<K,V> ch = p;
                     while (parent != null && ch == parent.left) {
                         ch = parent;
                         parent = parent.parent;
                     }
                     return parent;
                 }
             } else
                 return p;
 
         }
         return null;
     }

    
Gets the entry for the least key greater than 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 returns null.
 
     final Entry<K,V> getHigherEntry(K key) {
         Entry<K,V> p = ;
         while (p != null) {
             int cmp = compare(keyp.key);
             if (cmp < 0) {
                 if (p.left != null)
                     p = p.left;
                 else
                     return p;
             } else {
                 if (p.right != null) {
                     p = p.right;
                 } else {
                     Entry<K,V> parent = p.parent;
                     Entry<K,V> ch = p;
                     while (parent != null && ch == parent.right) {
                         ch = parent;
                         parent = parent.parent;
                     }
                     return parent;
                 }
             }
         }
         return null;
     }

    
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 null.
 
     final Entry<K,V> getLowerEntry(K key) {
         Entry<K,V> p = ;
         while (p != null) {
             int cmp = compare(keyp.key);
             if (cmp > 0) {
                 if (p.right != null)
                     p = p.right;
                 else
                     return p;
             } else {
                 if (p.left != null) {
                     p = p.left;
                 } else {
                     Entry<K,V> parent = p.parent;
                     Entry<K,V> ch = p;
                     while (parent != null && ch == parent.left) {
                         ch = parent;
                         parent = parent.parent;
                     }
                     return parent;
                 }
             }
         }
         return null;
     }

    
Associates the specified value with the specified key in this map. If the map previously contained a mapping for the key, the old value is replaced.

Parameters:
key key with which the specified value is to be associated
value value to be associated with the specified key
Returns:
the previous value associated with key, or null if there was no mapping for key. (A null return can also indicate that the map previously associated null with key.)
Throws:
java.lang.ClassCastException if the specified key cannot be compared with the keys currently in the map
java.lang.NullPointerException if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys
 
     public V put(K key, V value) {
         Entry<K,V> t = ;
         if (t == null) {
             // TBD:
             // 5045147: (coll) Adding null to an empty TreeSet should
             // throw NullPointerException
             //
             // compare(key, key); // type check
              = new Entry<K,V>(keyvaluenull);
              = 1;
             ++;
             return null;
         }
         int cmp;
         Entry<K,V> parent;
         // split comparator and comparable paths
         Comparator<? super K> cpr = ;
         if (cpr != null) {
             do {
                 parent = t;
                 cmp = cpr.compare(keyt.key);
                 if (cmp < 0)
                     t = t.left;
                 else if (cmp > 0)
                     t = t.right;
                 else
                     return t.setValue(value);
             } while (t != null);
         }
         else {
             if (key == null)
                 throw new NullPointerException();
             Comparable<? super K> k = (Comparable<? super K>) key;
             do {
                 parent = t;
                 cmp = k.compareTo(t.key);
                 if (cmp < 0)
                     t = t.left;
                 else if (cmp > 0)
                     t = t.right;
                 else
                     return t.setValue(value);
             } while (t != null);
         }
         Entry<K,V> e = new Entry<K,V>(keyvalueparent);
         if (cmp < 0)
             parent.left = e;
         else
             parent.right = e;
         fixAfterInsertion(e);
         ++;
         ++;
         return null;
     }

    
Removes the mapping for this key from this TreeMap if present.

Parameters:
key key for which mapping should be removed
Returns:
the previous value associated with key, or null if there was no mapping for key. (A null return can also indicate that the map previously associated null with key.)
Throws:
java.lang.ClassCastException if the specified key cannot be compared with the keys currently in the map
java.lang.NullPointerException if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys
 
     public V remove(Object key) {
         Entry<K,V> p = getEntry(key);
         if (p == null)
             return null;
 
         V oldValue = p.value;
         deleteEntry(p);
         return oldValue;
     }

    
Removes all of the mappings from this map. The map will be empty after this call returns.
 
     public void clear() {
         ++;
          = 0;
          = null;
     }

    
Returns a shallow copy of this TreeMap instance. (The keys and values themselves are not cloned.)

Returns:
a shallow copy of this map
 
     public Object clone() {
         TreeMap<K,V> clone = null;
         try {
             clone = (TreeMap<K,V>) super.clone();
         } catch (CloneNotSupportedException e) {
             throw new InternalError();
         }
 
         // Put clone into "virgin" state (except for comparator)
         clone.root = null;
         clone.size = 0;
         clone.modCount = 0;
         clone.entrySet = null;
         clone.navigableKeySet = null;
         clone.descendingMap = null;
 
         // Initialize clone with our mappings
         try {
             clone.buildFromSorted(entrySet().iterator(), nullnull);
         } catch (java.io.IOException cannotHappen) {
         } catch (ClassNotFoundException cannotHappen) {
         }
 
         return clone;
     }
 
     // NavigableMap API methods
 
    

Since:
1.6
 
     public Map.Entry<K,V> firstEntry() {
         return exportEntry(getFirstEntry());
     }

    

Since:
1.6
 
     public Map.Entry<K,V> lastEntry() {
         return exportEntry(getLastEntry());
     }

    

Since:
1.6
 
     public Map.Entry<K,V> pollFirstEntry() {
         Entry<K,V> p = getFirstEntry();
         Map.Entry<K,V> result = exportEntry(p);
         if (p != null)
             deleteEntry(p);
         return result;
     }

    

Since:
1.6
 
     public Map.Entry<K,V> pollLastEntry() {
         Entry<K,V> p = getLastEntry();
         Map.Entry<K,V> result = exportEntry(p);
         if (p != null)
             deleteEntry(p);
         return result;
     }

    

Throws:
java.lang.ClassCastException
java.lang.NullPointerException if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys
Since:
1.6
 
     public Map.Entry<K,V> lowerEntry(K key) {
         return exportEntry(getLowerEntry(key));
     }

    

Throws:
java.lang.ClassCastException
java.lang.NullPointerException if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys
Since:
1.6
 
     public K lowerKey(K key) {
         return keyOrNull(getLowerEntry(key));
     }

    

Throws:
java.lang.ClassCastException
java.lang.NullPointerException if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys
Since:
1.6
 
     public Map.Entry<K,V> floorEntry(K key) {
         return exportEntry(getFloorEntry(key));
     }

    

Throws:
java.lang.ClassCastException
java.lang.NullPointerException if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys
Since:
1.6
 
     public K floorKey(K key) {
         return keyOrNull(getFloorEntry(key));
     }

    

Throws:
java.lang.ClassCastException
java.lang.NullPointerException if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys
Since:
1.6
 
     public Map.Entry<K,V> ceilingEntry(K key) {
         return exportEntry(getCeilingEntry(key));
     }

    

Throws:
java.lang.ClassCastException
java.lang.NullPointerException if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys
Since:
1.6
 
     public K ceilingKey(K key) {
         return keyOrNull(getCeilingEntry(key));
     }

    

Throws:
java.lang.ClassCastException
java.lang.NullPointerException if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys
Since:
1.6
 
     public Map.Entry<K,V> higherEntry(K key) {
         return exportEntry(getHigherEntry(key));
     }

    

Throws:
java.lang.ClassCastException
java.lang.NullPointerException if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys
Since:
1.6
 
     public K higherKey(K key) {
         return keyOrNull(getHigherEntry(key));
     }
 
     // Views
 
    
Fields initialized to contain an instance of the entry set view the first time this view is requested. Views are stateless, so there's no reason to create more than one.
 
     private transient EntrySet entrySet = null;
     private transient KeySet<K> navigableKeySet = null;
     private transient NavigableMap<K,V> descendingMap = null;

    
Returns a Set view of the keys contained in this map. The set's iterator returns the keys in ascending order. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa. If the map is modified while an iteration over the set is in progress (except through the iterator's own remove operation), the results of the iteration are undefined. The set supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Set.remove, removeAll, retainAll, and clear operations. It does not support the add or addAll operations.
 
     public Set<K> keySet() {
         return navigableKeySet();
     }

    

Since:
1.6
 
     public NavigableSet<K> navigableKeySet() {
         KeySet<K> nks = ;
         return (nks != null) ? nks : ( = new KeySet(this));
     }

    

Since:
1.6
 
     public NavigableSet<K> descendingKeySet() {
         return descendingMap().navigableKeySet();
     }

    
Returns a Collection view of the values contained in this map. The collection's iterator returns the values in ascending order of the corresponding keys. The collection is backed by the map, so changes to the map are reflected in the collection, and vice-versa. If the map is modified while an iteration over the collection is in progress (except through the iterator's own remove operation), the results of the iteration are undefined. The collection supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Collection.remove, removeAll, retainAll and clear operations. It does not support the add or addAll operations.
 
     public Collection<V> values() {
         Collection<V> vs = ;
         return (vs != null) ? vs : ( = new Values());
     }

    
Returns a Set view of the mappings contained in this map. The set's iterator returns the entries in ascending key order. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa. If the map is modified while an iteration over the set is in progress (except through the iterator's own remove operation, or through the setValue operation on a map entry returned by the iterator) the results of the iteration are undefined. The set supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Set.remove, removeAll, retainAll and clear operations. It does not support the add or addAll operations.
 
     public Set<Map.Entry<K,V>> entrySet() {
         EntrySet es = ;
         return (es != null) ? es : ( = new EntrySet());
     }

    

Since:
1.6
 
     public NavigableMap<K, V> descendingMap() {
         NavigableMap<K, V> km = ;
         return (km != null) ? km :
             ( = new DescendingSubMap(this,
                                                   truenulltrue,
                                                   truenulltrue));
     }

    

Throws:
java.lang.ClassCastException
java.lang.NullPointerException if fromKey or toKey is null and this map uses natural ordering, or its comparator does not permit null keys
java.lang.IllegalArgumentException
Since:
1.6
 
     public NavigableMap<K,V> subMap(K fromKeyboolean fromInclusive,
                                     K toKey,   boolean toInclusive) {
         return new AscendingSubMap(this,
                                    falsefromKeyfromInclusive,
                                    falsetoKey,   toInclusive);
     }

    

Throws:
java.lang.ClassCastException
java.lang.NullPointerException if toKey is null and this map uses natural ordering, or its comparator does not permit null keys
java.lang.IllegalArgumentException
Since:
1.6
 
     public NavigableMap<K,V> headMap(K toKeyboolean inclusive) {
         return new AscendingSubMap(this,
                                    true,  null,  true,
                                    falsetoKeyinclusive);
     }

    

Throws:
java.lang.ClassCastException
java.lang.NullPointerException if fromKey is null and this map uses natural ordering, or its comparator does not permit null keys
java.lang.IllegalArgumentException
Since:
1.6
 
     public NavigableMap<K,V> tailMap(K fromKeyboolean inclusive) {
         return new AscendingSubMap(this,
                                    falsefromKeyinclusive,
                                    true,  null,    true);
     }

    

Throws:
java.lang.ClassCastException
java.lang.NullPointerException if fromKey or toKey is null and this map uses natural ordering, or its comparator does not permit null keys
java.lang.IllegalArgumentException
 
     public SortedMap<K,V> subMap(K fromKey, K toKey) {
         return subMap(fromKeytruetoKeyfalse);
     }

    

Throws:
java.lang.ClassCastException
java.lang.NullPointerException if toKey is null and this map uses natural ordering, or its comparator does not permit null keys
java.lang.IllegalArgumentException
 
     public SortedMap<K,V> headMap(K toKey) {
         return headMap(toKeyfalse);
     }

    

Throws:
java.lang.ClassCastException
java.lang.NullPointerException if fromKey is null and this map uses natural ordering, or its comparator does not permit null keys
java.lang.IllegalArgumentException
 
     public SortedMap<K,V> tailMap(K fromKey) {
         return tailMap(fromKeytrue);
     }
 
     // View class support
 
     class Values extends AbstractCollection<V> {
         public Iterator<V> iterator() {
             return new ValueIterator(getFirstEntry());
         }
 
         public int size() {
             return TreeMap.this.size();
         }
 
         public boolean contains(Object o) {
             return TreeMap.this.containsValue(o);
         }
 
         public boolean remove(Object o) {
             for (Entry<K,V> e = getFirstEntry(); e != nulle = successor(e)) {
                 if (valEquals(e.getValue(), o)) {
                     deleteEntry(e);
                     return true;
                 }
             }
             return false;
         }
 
         public void clear() {
             TreeMap.this.clear();
         }
     }
 
     class EntrySet extends AbstractSet<Map.Entry<K,V>> {
         public Iterator<Map.Entry<K,V>> iterator() {
             return new EntryIterator(getFirstEntry());
         }
 
         public boolean contains(Object o) {
             if (!(o instanceof Map.Entry))
                 return false;
             Map.Entry<K,V> entry = (Map.Entry<K,V>) o;
             V value = entry.getValue();
             Entry<K,V> p = getEntry(entry.getKey());
             return p != null && valEquals(p.getValue(), value);
         }
 
         public boolean remove(Object o) {
             if (!(o instanceof Map.Entry))
                 return false;
             Map.Entry<K,V> entry = (Map.Entry<K,V>) o;
             V value = entry.getValue();
             Entry<K,V> p = getEntry(entry.getKey());
             if (p != null && valEquals(p.getValue(), value)) {
                 deleteEntry(p);
                 return true;
             }
             return false;
        }
        public int size() {
            return TreeMap.this.size();
        }
        public void clear() {
            TreeMap.this.clear();
        }
    }
    /*
     * Unlike Values and EntrySet, the KeySet class is static,
     * delegating to a NavigableMap to allow use by SubMaps, which
     * outweighs the ugliness of needing type-tests for the following
     * Iterator methods that are defined appropriately in main versus
     * submap classes.
     */
    Iterator<K> keyIterator() {
        return new KeyIterator(getFirstEntry());
    }
        return new DescendingKeyIterator(getLastEntry());
    }
    static final class KeySet<E> extends AbstractSet<E> implements NavigableSet<E> {
        private final NavigableMap<E, Objectm;
        KeySet(NavigableMap<E,Objectmap) {  = map; }
        public Iterator<E> iterator() {
            if ( instanceof TreeMap)
                return ((TreeMap<E,Object>)).keyIterator();
            else
                return (Iterator<E>)(((TreeMap.NavigableSubMap)).keyIterator());
        }
        public Iterator<E> descendingIterator() {
            if ( instanceof TreeMap)
                return ((TreeMap<E,Object>)).descendingKeyIterator();
            else
                return (Iterator<E>)(((TreeMap.NavigableSubMap)).descendingKeyIterator());
        }
        public int size() { return .size(); }
        public boolean isEmpty() { return .isEmpty(); }
        public boolean contains(Object o) { return .containsKey(o); }
        public void clear() { .clear(); }
        public E lower(E e) { return .lowerKey(e); }
        public E floor(E e) { return .floorKey(e); }
        public E ceiling(E e) { return .ceilingKey(e); }
        public E higher(E e) { return .higherKey(e); }
        public E first() { return .firstKey(); }
        public E last() { return .lastKey(); }
        public Comparator<? super E> comparator() { return .comparator(); }
        public E pollFirst() {
            Map.Entry<E,Objecte = .pollFirstEntry();
            return e == nullnull : e.getKey();
        }
        public E pollLast() {
            Map.Entry<E,Objecte = .pollLastEntry();
            return e == nullnull : e.getKey();
        }
        public boolean remove(Object o) {
            int oldSize = size();
            .remove(o);
            return size() != oldSize;
        }
        public NavigableSet<E> subSet(E fromElementboolean fromInclusive,
                                      E toElement,   boolean toInclusive) {
            return new TreeSet<E>(.subMap(fromElementfromInclusive,
                                           toElement,   toInclusive));
        }
        public NavigableSet<E> headSet(E toElementboolean inclusive) {
            return new TreeSet<E>(.headMap(toElementinclusive));
        }
        public NavigableSet<E> tailSet(E fromElementboolean inclusive) {
            return new TreeSet<E>(.tailMap(fromElementinclusive));
        }
        public SortedSet<E> subSet(E fromElement, E toElement) {
            return subSet(fromElementtruetoElementfalse);
        }
        public SortedSet<E> headSet(E toElement) {
            return headSet(toElementfalse);
        }
        public SortedSet<E> tailSet(E fromElement) {
            return tailSet(fromElementtrue);
        }
        public NavigableSet<E> descendingSet() {
            return new TreeSet(.descendingMap());
        }
    }

    
Base class for TreeMap Iterators
    abstract class PrivateEntryIterator<T> implements Iterator<T> {
        Entry<K,V> next;
        Entry<K,V> lastReturned;
        int expectedModCount;
        PrivateEntryIterator(Entry<K,V> first) {
             = ;
             = null;
             = first;
        }
        public final boolean hasNext() {
            return  != null;
        }
        final Entry<K,V> nextEntry() {
            Entry<K,V> e = ;
            if (e == null)
                throw new NoSuchElementException();
            if ( != )
                throw new ConcurrentModificationException();
             = successor(e);
             = e;
            return e;
        }
        final Entry<K,V> prevEntry() {
            Entry<K,V> e = ;
            if (e == null)
                throw new NoSuchElementException();
            if ( != )
                throw new ConcurrentModificationException();
             = predecessor(e);
             = e;
            return e;
        }
        public void remove() {
            if ( == null)
                throw new IllegalStateException();
            if ( != )
                throw new ConcurrentModificationException();
            // deleted entries are replaced by their successors
            if (. != null && . != null)
                 = ;
            deleteEntry();
             = ;
             = null;
        }
    }
    final class EntryIterator extends PrivateEntryIterator<Map.Entry<K,V>> {
        EntryIterator(Entry<K,V> first) {
            super(first);
        }
        public Map.Entry<K,V> next() {
            return nextEntry();
        }
    }
    final class ValueIterator extends PrivateEntryIterator<V> {
        ValueIterator(Entry<K,V> first) {
            super(first);
        }
        public V next() {
            return nextEntry().;
        }
    }
    final class KeyIterator extends PrivateEntryIterator<K> {
        KeyIterator(Entry<K,V> first) {
            super(first);
        }
        public K next() {
            return nextEntry().;
        }
    }
    final class DescendingKeyIterator extends PrivateEntryIterator<K> {
        DescendingKeyIterator(Entry<K,V> first) {
            super(first);
        }
        public K next() {
            return prevEntry().;
        }
    }
    // Little utilities

    
Compares two keys using the correct comparison method for this TreeMap.
    final int compare(Object k1Object k2) {
        return ==null ? ((Comparable<? super K>)k1).compareTo((K)k2)
            : .compare((K)k1, (K)k2);
    }

    
Test two values for equality. Differs from o1.equals(o2) only in that it copes with null o1 properly.
    final static boolean valEquals(Object o1Object o2) {
        return (o1==null ? o2==null : o1.equals(o2));
    }

    
Return SimpleImmutableEntry for entry, or null if null
    static <K,V> Map.Entry<K,V> exportEntry(TreeMap.Entry<K,V> e) {
        return e == nullnull :
            new AbstractMap.SimpleImmutableEntry<K,V>(e);
    }

    
Return key for entry, or null if null
    static <K,V> K keyOrNull(TreeMap.Entry<K,V> e) {
        return e == nullnull : e.key;
    }

    
Returns the key corresponding to the specified Entry.

Throws:
NoSuchElementException if the Entry is null
    static <K> K key(Entry<K,?> e) {
        if (e==null)
            throw new NoSuchElementException();
        return e.key;
    }
    // SubMaps

    
Dummy value serving as unmatchable fence key for unbounded SubMapIterators
    private static final Object UNBOUNDED = new Object();

    

Serial:
include
    static abstract class NavigableSubMap<K,V> extends AbstractMap<K,V>
        implements NavigableMap<K,V>, java.io.Serializable {
        
The backing map.
        final TreeMap<K,V> m;

        
Endpoints are represented as triples (fromStart, lo, loInclusive) and (toEnd, hi, hiInclusive). If fromStart is true, then the low (absolute) bound is the start of the backing map, and the other values are ignored. Otherwise, if loInclusive is true, lo is the inclusive bound, else lo is the exclusive bound. Similarly for the upper bound.
        final K lohi;
        final boolean fromStarttoEnd;
        final boolean loInclusivehiInclusive;
        NavigableSubMap(TreeMap<K,V> m,
                        boolean fromStart, K loboolean loInclusive,
                        boolean toEnd,     K hiboolean hiInclusive) {
            if (!fromStart && !toEnd) {
                if (m.compare(lohi) > 0)
                    throw new IllegalArgumentException("fromKey > toKey");
            } else {
                if (!fromStart// type check
                    m.compare(lolo);
                if (!toEnd)
                    m.compare(hihi);
            }
            this. = m;
            this. = fromStart;
            this. = lo;
            this. = loInclusive;
            this. = toEnd;
            this. = hi;
            this. = hiInclusive;
        }
        // internal utilities
        final boolean tooLow(Object key) {
            if (!) {
                int c = .compare(key);
                if (c < 0 || (c == 0 && !))
                    return true;
            }
            return false;
        }
        final boolean tooHigh(Object key) {
            if (!) {
                int c = .compare(key);
                if (c > 0 || (c == 0 && !))
                    return true;
            }
            return false;
        }
        final boolean inRange(Object key) {
            return !tooLow(key) && !tooHigh(key);
        }
        final boolean inClosedRange(Object key) {
            return ( || .compare(key) >= 0)
                && ( || .compare(key) >= 0);
        }
        final boolean inRange(Object keyboolean inclusive) {
            return inclusive ? inRange(key) : inClosedRange(key);
        }
        /*
         * Absolute versions of relation operations.
         * Subclasses map to these using like-named "sub"
         * versions that invert senses for descending maps
         */
        final TreeMap.Entry<K,V> absLowest() {
            TreeMap.Entry<K,V> e =
                ( ?  .getFirstEntry() :
                 ( ? .getCeilingEntry() :
                                .getHigherEntry()));
            return (e == null || tooHigh(e.key)) ? null : e;
        }
        final TreeMap.Entry<K,V> absHighest() {
            TreeMap.Entry<K,V> e =
                ( ?  .getLastEntry() :
                 ( ?  .getFloorEntry() :
                                 .getLowerEntry()));
            return (e == null || tooLow(e.key)) ? null : e;
        }
        final TreeMap.Entry<K,V> absCeiling(K key) {
            if (tooLow(key))
                return absLowest();
            TreeMap.Entry<K,V> e = .getCeilingEntry(key);
            return (e == null || tooHigh(e.key)) ? null : e;
        }
        final TreeMap.Entry<K,V> absHigher(K key) {
            if (tooLow(key))
                return absLowest();
            TreeMap.Entry<K,V> e = .getHigherEntry(key);
            return (e == null || tooHigh(e.key)) ? null : e;
        }
        final TreeMap.Entry<K,V> absFloor(K key) {
            if (tooHigh(key))
                return absHighest();
            TreeMap.Entry<K,V> e = .getFloorEntry(key);
            return (e == null || tooLow(e.key)) ? null : e;
        }
        final TreeMap.Entry<K,V> absLower(K key) {
            if (tooHigh(key))
                return absHighest();
            TreeMap.Entry<K,V> e = .getLowerEntry(key);
            return (e == null || tooLow(e.key)) ? null : e;
        }

        
Returns the absolute high fence for ascending traversal
        final TreeMap.Entry<K,V> absHighFence() {
            return ( ? null : ( ?
                                    .getHigherEntry() :
                                    .getCeilingEntry()));
        }

        
Return the absolute low fence for descending traversal
        final TreeMap.Entry<K,V> absLowFence() {
            return ( ? null : ( ?
                                        .getLowerEntry() :
                                        .getFloorEntry()));
        }
        // Abstract methods defined in ascending vs descending classes
        // These relay to the appropriate absolute versions
        abstract TreeMap.Entry<K,V> subLowest();
        abstract TreeMap.Entry<K,V> subHighest();
        abstract TreeMap.Entry<K,V> subCeiling(K key);
        abstract TreeMap.Entry<K,V> subHigher(K key);
        abstract TreeMap.Entry<K,V> subFloor(K key);
        abstract TreeMap.Entry<K,V> subLower(K key);

        
Returns ascending iterator from the perspective of this submap
        abstract Iterator<K> keyIterator();

        
Returns descending iterator from the perspective of this submap
        abstract Iterator<K> descendingKeyIterator();
        // public methods
        public boolean isEmpty() {
            return ( && ) ? .isEmpty() : entrySet().isEmpty();
        }
        public int size() {
            return ( && ) ? .size() : entrySet().size();
        }
        public final boolean containsKey(Object key) {
            return inRange(key) && .containsKey(key);
        }
        public final V put(K key, V value) {
            if (!inRange(key))
                throw new IllegalArgumentException("key out of range");
            return .put(keyvalue);
        }
        public final V get(Object key) {
            return !inRange(key)? null :  .get(key);
        }
        public final V remove(Object key) {
            return !inRange(key)? null  : .remove(key);
        }
        public final Map.Entry<K,V> ceilingEntry(K key) {
            return exportEntry(subCeiling(key));
        }
        public final K ceilingKey(K key) {
            return keyOrNull(subCeiling(key));
        }
        public final Map.Entry<K,V> higherEntry(K key) {
            return exportEntry(subHigher(key));
        }
        public final K higherKey(K key) {
            return keyOrNull(subHigher(key));
        }
        public final Map.Entry<K,V> floorEntry(K key) {
            return exportEntry(subFloor(key));
        }
        public final K floorKey(K key) {
            return keyOrNull(subFloor(key));
        }
        public final Map.Entry<K,V> lowerEntry(K key) {
            return exportEntry(subLower(key));
        }
        public final K lowerKey(K key) {
            return keyOrNull(subLower(key));
        }
        public final K firstKey() {
            return key(subLowest());
        }
        public final K lastKey() {
            return key(subHighest());
        }
        public final Map.Entry<K,V> firstEntry() {
            return exportEntry(subLowest());
        }
        public final Map.Entry<K,V> lastEntry() {
            return exportEntry(subHighest());
        }
        public final Map.Entry<K,V> pollFirstEntry() {
            TreeMap.Entry<K,V> e = subLowest();
            Map.Entry<K,V> result = exportEntry(e);
            if (e != null)
                .deleteEntry(e);
            return result;
        }
        public final Map.Entry<K,V> pollLastEntry() {
            TreeMap.Entry<K,V> e = subHighest();
            Map.Entry<K,V> result = exportEntry(e);
            if (e != null)
                .deleteEntry(e);
            return result;
        }
        // Views
        transient NavigableMap<K,V> descendingMapView = null;
        transient EntrySetView entrySetView = null;
        transient KeySet<K> navigableKeySetView = null;
        public final NavigableSet<K> navigableKeySet() {
            KeySet<K> nksv = ;
            return (nksv != null) ? nksv :
                ( = new TreeMap.KeySet(this));
        }
        public final Set<K> keySet() {
            return navigableKeySet();
        }
        public NavigableSet<K> descendingKeySet() {
            return descendingMap().navigableKeySet();
        }
        public final SortedMap<K,V> subMap(K fromKey, K toKey) {
            return subMap(fromKeytruetoKeyfalse);
        }
        public final SortedMap<K,V> headMap(K toKey) {
            return headMap(toKeyfalse);
        }
        public final SortedMap<K,V> tailMap(K fromKey) {
            return tailMap(fromKeytrue);
        }
        // View classes
        abstract class EntrySetView extends AbstractSet<Map.Entry<K,V>> {
            private transient int size = -1, sizeModCount;
            public int size() {
                if ( && )
                    return .size();
                if ( == -1 ||  != .) {
                     = .;
                     = 0;
                    Iterator i = iterator();
                    while (i.hasNext()) {
                        ++;
                        i.next();
                    }
                }
                return ;
            }
            public boolean isEmpty() {
                TreeMap.Entry<K,V> n = absLowest();
                return n == null || tooHigh(n.key);
            }
            public boolean contains(Object o) {
                if (!(o instanceof Map.Entry))
                    return false;
                Map.Entry<K,V> entry = (Map.Entry<K,V>) o;
                K key = entry.getKey();
                if (!inRange(key))
                    return false;
                TreeMap.Entry node = .getEntry(key);
                return node != null &&
                    valEquals(node.getValue(), entry.getValue());
            }
            public boolean remove(Object o) {
                if (!(o instanceof Map.Entry))
                    return false;
                Map.Entry<K,V> entry = (Map.Entry<K,V>) o;
                K key = entry.getKey();
                if (!inRange(key))
                    return false;
                TreeMap.Entry<K,V> node = .getEntry(key);
                if (node!=null && valEquals(node.getValue(),entry.getValue())){
                    .deleteEntry(node);
                    return true;
                }
                return false;
            }
        }

        
Iterators for SubMaps
        abstract class SubMapIterator<T> implements Iterator<T> {
            TreeMap.Entry<K,V> lastReturned;
            TreeMap.Entry<K,V> next;
            final Object fenceKey;
            int expectedModCount;
            SubMapIterator(TreeMap.Entry<K,V> first,
                           TreeMap.Entry<K,V> fence) {
                 = .;
                 = null;
                 = first;
                 = fence == null ?  : fence.key;
            }
            public final boolean hasNext() {
                return  != null && . != ;
            }
            final TreeMap.Entry<K,V> nextEntry() {
                TreeMap.Entry<K,V> e = ;
                if (e == null || e.key == )
                    throw new NoSuchElementException();
                if (. != )
                    throw new ConcurrentModificationException();
                 = successor(e);
                 = e;
                return e;
            }
            final TreeMap.Entry<K,V> prevEntry() {
                TreeMap.Entry<K,V> e = ;
                if (e == null || e.key == )
                    throw new NoSuchElementException();
                if (. != )
                    throw new ConcurrentModificationException();
                 = predecessor(e);
                 = e;
                return e;
            }
            final void removeAscending() {
                if ( == null)
                    throw new IllegalStateException();
                if (. != )
                    throw new ConcurrentModificationException();
                // deleted entries are replaced by their successors
                if (. != null && . != null)
                     = ;
                .deleteEntry();
                 = null;
                 = .;
            }
            final void removeDescending() {
                if ( == null)
                    throw new IllegalStateException();
                if (. != )
                    throw new ConcurrentModificationException();
                .deleteEntry();
                 = null;
                 = .;
            }
        }
        final class SubMapEntryIterator extends SubMapIterator<Map.Entry<K,V>> {
            SubMapEntryIterator(TreeMap.Entry<K,V> first,
                                TreeMap.Entry<K,V> fence) {
                super(firstfence);
            }
            public Map.Entry<K,V> next() {
                return nextEntry();
            }
            public void remove() {
                removeAscending();
            }
        }
        final class SubMapKeyIterator extends SubMapIterator<K> {
            SubMapKeyIterator(TreeMap.Entry<K,V> first,
                              TreeMap.Entry<K,V> fence) {
                super(firstfence);
            }
            public K next() {
                return nextEntry().;
            }
            public void remove() {
                removeAscending();
            }
        }
        final class DescendingSubMapEntryIterator extends SubMapIterator<Map.Entry<K,V>> {
            DescendingSubMapEntryIterator(TreeMap.Entry<K,V> last,
                                          TreeMap.Entry<K,V> fence) {
                super(lastfence);
            }
            public Map.Entry<K,V> next() {
                return prevEntry();
            }
            public void remove() {
                removeDescending();
            }
        }
        final class DescendingSubMapKeyIterator extends SubMapIterator<K> {
            DescendingSubMapKeyIterator(TreeMap.Entry<K,V> last,
                                        TreeMap.Entry<K,V> fence) {
                super(lastfence);
            }
            public K next() {
                return prevEntry().;
            }
            public void remove() {
                removeDescending();
            }
        }
    }

    

Serial:
include
    static final class AscendingSubMap<K,V> extends NavigableSubMap<K,V> {
        private static final long serialVersionUID = 912986545866124060L;
        AscendingSubMap(TreeMap<K,V> m,
                        boolean fromStart, K loboolean loInclusive,
                        boolean toEnd,     K hiboolean hiInclusive) {
            super(mfromStartloloInclusivetoEndhihiInclusive);
        }
        public Comparator<? super K> comparator() {
            return .comparator();
        }
        public NavigableMap<K,V> subMap(K fromKeyboolean fromInclusive,
                                        K toKey,   boolean toInclusive) {
            if (!inRange(fromKeyfromInclusive))
                throw new IllegalArgumentException("fromKey out of range");
            if (!inRange(toKeytoInclusive))
                throw new IllegalArgumentException("toKey out of range");
            return new AscendingSubMap(,
                                       falsefromKeyfromInclusive,
                                       falsetoKey,   toInclusive);
        }
        public NavigableMap<K,V> headMap(K toKeyboolean inclusive) {
            if (!inRange(toKeyinclusive))
                throw new IllegalArgumentException("toKey out of range");
            return new AscendingSubMap(,
                                       ,    ,
                                       false,     toKeyinclusive);
        }
        public NavigableMap<K,V> tailMap(K fromKeyboolean inclusive){
            if (!inRange(fromKeyinclusive))
                throw new IllegalArgumentException("fromKey out of range");
            return new AscendingSubMap(,
                                       falsefromKeyinclusive,
                                       ,      );
        }
        public NavigableMap<K,V> descendingMap() {
            NavigableMap<K,V> mv = ;
            return (mv != null) ? mv :
                ( =
                 new DescendingSubMap(,
                                      ,
                                      ,     ));
        }
        Iterator<K> keyIterator() {
            return new SubMapKeyIterator(absLowest(), absHighFence());
        }
        Iterator<K> descendingKeyIterator() {
            return new DescendingSubMapKeyIterator(absHighest(), absLowFence());
        }
        final class AscendingEntrySetView extends EntrySetView {
            public Iterator<Map.Entry<K,V>> iterator() {
                return new SubMapEntryIterator(absLowest(), absHighFence());
            }
        }
        public Set<Map.Entry<K,V>> entrySet() {
            EntrySetView es = ;
            return (es != null) ? es : new AscendingEntrySetView();
        }
        TreeMap.Entry<K,V> subLowest()       { return absLowest(); }
        TreeMap.Entry<K,V> subHighest()      { return absHighest(); }
        TreeMap.Entry<K,V> subCeiling(K key) { return absCeiling(key); }
        TreeMap.Entry<K,V> subHigher(K key)  { return absHigher(key); }
        TreeMap.Entry<K,V> subFloor(K key)   { return absFloor(key); }
        TreeMap.Entry<K,V> subLower(K key)   { return absLower(key); }
    }

    

Serial:
include
    static final class DescendingSubMap<K,V>  extends NavigableSubMap<K,V> {
        private static final long serialVersionUID = 912986545866120460L;
        DescendingSubMap(TreeMap<K,V> m,
                        boolean fromStart, K loboolean loInclusive,
                        boolean toEnd,     K hiboolean hiInclusive) {
            super(mfromStartloloInclusivetoEndhihiInclusive);
        }
        private final Comparator<? super K> reverseComparator =
            Collections.reverseOrder(.);
        public Comparator<? super K> comparator() {
            return ;
        }
        public NavigableMap<K,V> subMap(K fromKeyboolean fromInclusive,
                                        K toKey,   boolean toInclusive) {
            if (!inRange(fromKeyfromInclusive))
                throw new IllegalArgumentException("fromKey out of range");
            if (!inRange(toKeytoInclusive))
                throw new IllegalArgumentException("toKey out of range");
            return new DescendingSubMap(,
                                        falsetoKey,   toInclusive,
                                        falsefromKeyfromInclusive);
        }
        public NavigableMap<K,V> headMap(K toKeyboolean inclusive) {
            if (!inRange(toKeyinclusive))
                throw new IllegalArgumentException("toKey out of range");
            return new DescendingSubMap(,
                                        falsetoKeyinclusive,
                                        ,    );
        }
        public NavigableMap<K,V> tailMap(K fromKeyboolean inclusive){
            if (!inRange(fromKeyinclusive))
                throw new IllegalArgumentException("fromKey out of range");
            return new DescendingSubMap(,
                                        ,
                                        falsefromKeyinclusive);
        }
        public NavigableMap<K,V> descendingMap() {
            NavigableMap<K,V> mv = ;
            return (mv != null) ? mv :
                ( =
                 new AscendingSubMap(,
                                     ,
                                     ,     ));
        }
        Iterator<K> keyIterator() {
            return new DescendingSubMapKeyIterator(absHighest(), absLowFence());
        }
        Iterator<K> descendingKeyIterator() {
            return new SubMapKeyIterator(absLowest(), absHighFence());
        }
        final class DescendingEntrySetView extends EntrySetView {
            public Iterator<Map.Entry<K,V>> iterator() {
                return new DescendingSubMapEntryIterator(absHighest(), absLowFence());
            }
        }
        public Set<Map.Entry<K,V>> entrySet() {
            EntrySetView es = ;
            return (es != null) ? es : new DescendingEntrySetView();
        }
        TreeMap.Entry<K,V> subLowest()       { return absHighest(); }
        TreeMap.Entry<K,V> subHighest()      { return absLowest(); }
        TreeMap.Entry<K,V> subCeiling(K key) { return absFloor(key); }
        TreeMap.Entry<K,V> subHigher(K key)  { return absLower(key); }
        TreeMap.Entry<K,V> subFloor(K key)   { return absCeiling(key); }
        TreeMap.Entry<K,V> subLower(K key)   { return absHigher(key); }
    }

    
This class exists solely for the sake of serialization compatibility with previous releases of TreeMap that did not support NavigableMap. It translates an old-version SubMap into a new-version AscendingSubMap. This class is never otherwise used.

Serial:
include
    private class SubMap extends AbstractMap<K,V>
        implements SortedMap<K,V>, java.io.Serializable {
        private static final long serialVersionUID = -6520786458950516097L;
        private boolean fromStart = falsetoEnd = false;
        private K fromKeytoKey;
        private Object readResolve() {
            return new AscendingSubMap(TreeMap.this,
                                       true,
                                       false);
        }
        public Set<Map.Entry<K,V>> entrySet() { throw new InternalError(); }
        public K lastKey() { throw new InternalError(); }
        public K firstKey() { throw new InternalError(); }
        public SortedMap<K,V> subMap(K fromKey, K toKey) { throw new InternalError(); }
        public SortedMap<K,V> headMap(K toKey) { throw new InternalError(); }
        public SortedMap<K,V> tailMap(K fromKey) { throw new InternalError(); }
        public Comparator<? super K> comparator() { throw new InternalError(); }
    }
    // Red-black mechanics
    private static final boolean RED   = false;
    private static final boolean BLACK = true;

    
Node in the Tree. Doubles as a means to pass key-value pairs back to user (see Map.Entry).
    static final class Entry<K,V> implements Map.Entry<K,V> {
        K key;
        V value;
        Entry<K,V> left = null;
        Entry<K,V> right = null;
        Entry<K,V> parent;
        boolean color = ;

        
Make a new cell with given key, value, and parent, and with null child links, and BLACK color.
        Entry(K key, V valueEntry<K,V> parent) {
            this. = key;
            this. = value;
            this. = parent;
        }

        
Returns the key.

Returns:
the key
        public K getKey() {
            return ;
        }

        
Returns the value associated with the key.

Returns:
the value associated with the key
        public V getValue() {
            return ;
        }

        
Replaces the value currently associated with the key with the given value.

Returns:
the value associated with the key before this method was called
        public V setValue(V value) {
            V oldValue = this.;
            this. = value;
            return oldValue;
        }
        public boolean equals(Object o) {
            if (!(o instanceof Map.Entry))
                return false;
            Map.Entry<?,?> e = (Map.Entry<?,?>)o;
            return valEquals(,e.getKey()) && valEquals(,e.getValue());
        }
        public int hashCode() {
            int keyHash = (==null ? 0 : .hashCode());
            int valueHash = (==null ? 0 : .hashCode());
            return keyHash ^ valueHash;
        }
        public String toString() {
            return  + "=" + ;
        }
    }

    
Returns the first Entry in the TreeMap (according to the TreeMap's key-sort function). Returns null if the TreeMap is empty.
    final Entry<K,V> getFirstEntry() {
        Entry<K,V> p = ;
        if (p != null)
            while (p.left != null)
                p = p.left;
        return p;
    }

    
Returns the last Entry in the TreeMap (according to the TreeMap's key-sort function). Returns null if the TreeMap is empty.
    final Entry<K,V> getLastEntry() {
        Entry<K,V> p = ;
        if (p != null)
            while (p.right != null)
                p = p.right;
        return p;
    }

    
Returns the successor of the specified Entry, or null if no such.
    static <K,V> TreeMap.Entry<K,V> successor(Entry<K,V> t) {
        if (t == null)
            return null;
        else if (t.right != null) {
            Entry<K,V> p = t.right;
            while (p.left != null)
                p = p.left;
            return p;
        } else {
            Entry<K,V> p = t.parent;
            Entry<K,V> ch = t;
            while (p != null && ch == p.right) {
                ch = p;
                p = p.parent;
            }
            return p;
        }
    }

    
Returns the predecessor of the specified Entry, or null if no such.
    static <K,V> Entry<K,V> predecessor(Entry<K,V> t) {
        if (t == null)
            return null;
        else if (t.left != null) {
            Entry<K,V> p = t.left;
            while (p.right != null)
                p = p.right;
            return p;
        } else {
            Entry<K,V> p = t.parent;
            Entry<K,V> ch = t;
            while (p != null && ch == p.left) {
                ch = p;
                p = p.parent;
            }
            return p;
        }
    }

    
Balancing operations. Implementations of rebalancings during insertion and deletion are slightly different than the CLR version. Rather than using dummy nilnodes, we use a set of accessors that deal properly with null. They are used to avoid messiness surrounding nullness checks in the main algorithms.
    private static <K,V> boolean colorOf(Entry<K,V> p) {
        return (p == null ?  : p.color);
    }
    private static <K,V> Entry<K,V> parentOf(Entry<K,V> p) {
        return (p == null ? nullp.parent);
    }
    private static <K,V> void setColor(Entry<K,V> pboolean c) {
        if (p != null)
            p.color = c;
    }
    private static <K,V> Entry<K,V> leftOf(Entry<K,V> p) {
        return (p == null) ? nullp.left;
    }
    private static <K,V> Entry<K,V> rightOf(Entry<K,V> p) {
        return (p == null) ? nullp.right;
    }

    
From CLR
    private void rotateLeft(Entry<K,V> p) {
        if (p != null) {
            Entry<K,V> r = p.right;
            p.right = r.left;
            if (r.left != null)
                r.left.parent = p;
            r.parent = p.parent;
            if (p.parent == null)
                 = r;
            else if (p.parent.left == p)
                p.parent.left = r;
            else
                p.parent.right = r;
            r.left = p;
            p.parent = r;
        }
    }

    
From CLR
    private void rotateRight(Entry<K,V> p) {
        if (p != null) {
            Entry<K,V> l = p.left;
            p.left = l.right;
            if (l.right != nulll.right.parent = p;
            l.parent = p.parent;
            if (p.parent == null)
                 = l;
            else if (p.parent.right == p)
                p.parent.right = l;
            else p.parent.left = l;
            l.right = p;
            p.parent = l;
        }
    }

    
From CLR
    private void fixAfterInsertion(Entry<K,V> x) {
        x.color = ;
        while (x != null && x !=  && x.parent.color == ) {
            if (parentOf(x) == leftOf(parentOf(parentOf(x)))) {
                Entry<K,V> y = rightOf(parentOf(parentOf(x)));
                if (colorOf(y) == ) {
                    setColor(parentOf(x), );
                    setColor(y);
                    setColor(parentOf(parentOf(x)), );
                    x = parentOf(parentOf(x));
                } else {
                    if (x == rightOf(parentOf(x))) {
                        x = parentOf(x);
                        rotateLeft(x);
                    }
                    setColor(parentOf(x), );
                    setColor(parentOf(parentOf(x)), );
                    rotateRight(parentOf(parentOf(x)));
                }
            } else {
                Entry<K,V> y = leftOf(parentOf(parentOf(x)));
                if (colorOf(y) == ) {
                    setColor(parentOf(x), );
                    setColor(y);
                    setColor(parentOf(parentOf(x)), );
                    x = parentOf(parentOf(x));
                } else {
                    if (x == leftOf(parentOf(x))) {
                        x = parentOf(x);
                        rotateRight(x);
                    }
                    setColor(parentOf(x), );
                    setColor(parentOf(parentOf(x)), );
                    rotateLeft(parentOf(parentOf(x)));
                }
            }
        }
        . = ;
    }

    
Delete node p, and then rebalance the tree.
    private void deleteEntry(Entry<K,V> p) {
        ++;
        --;
        // If strictly internal, copy successor's element to p and then make p
        // point to successor.
        if (p.left != null && p.right != null) {
            Entry<K,V> s = successor (p);
            p.key = s.key;
            p.value = s.value;
            p = s;
        } // p has 2 children
        // Start fixup at replacement node, if it exists.
        Entry<K,V> replacement = (p.left != null ? p.left : p.right);
        if (replacement != null) {
            // Link replacement to parent
            replacement.parent = p.parent;
            if (p.parent == null)
                 = replacement;
            else if (p == p.parent.left)
                p.parent.left  = replacement;
            else
                p.parent.right = replacement;
            // Null out links so they are OK to use by fixAfterDeletion.
            p.left = p.right = p.parent = null;
            // Fix replacement
            if (p.color == )
                fixAfterDeletion(replacement);
        } else if (p.parent == null) { // return if we are the only node.
             = null;
        } else { //  No children. Use self as phantom replacement and unlink.
            if (p.color == )
                fixAfterDeletion(p);
            if (p.parent != null) {
                if (p == p.parent.left)
                    p.parent.left = null;
                else if (p == p.parent.right)
                    p.parent.right = null;
                p.parent = null;
            }
        }
    }

    
From CLR
    private void fixAfterDeletion(Entry<K,V> x) {
        while (x !=  && colorOf(x) == ) {
            if (x == leftOf(parentOf(x))) {
                Entry<K,V> sib = rightOf(parentOf(x));
                if (colorOf(sib) == ) {
                    setColor(sib);
                    setColor(parentOf(x), );
                    rotateLeft(parentOf(x));
                    sib = rightOf(parentOf(x));
                }
                if (colorOf(leftOf(sib))  ==  &&
                    colorOf(rightOf(sib)) == ) {
                    setColor(sib);
                    x = parentOf(x);
                } else {
                    if (colorOf(rightOf(sib)) == ) {
                        setColor(leftOf(sib), );
                        setColor(sib);
                        rotateRight(sib);
                        sib = rightOf(parentOf(x));
                    }
                    setColor(sibcolorOf(parentOf(x)));
                    setColor(parentOf(x), );
                    setColor(rightOf(sib), );
                    rotateLeft(parentOf(x));
                    x = ;
                }
            } else { // symmetric
                Entry<K,V> sib = leftOf(parentOf(x));
                if (colorOf(sib) == ) {
                    setColor(sib);
                    setColor(parentOf(x), );
                    rotateRight(parentOf(x));
                    sib = leftOf(parentOf(x));
                }
                if (colorOf(rightOf(sib)) ==  &&
                    colorOf(leftOf(sib)) == ) {
                    setColor(sib);
                    x = parentOf(x);
                } else {
                    if (colorOf(leftOf(sib)) == ) {
                        setColor(rightOf(sib), );
                        setColor(sib);
                        rotateLeft(sib);
                        sib = leftOf(parentOf(x));
                    }
                    setColor(sibcolorOf(parentOf(x)));
                    setColor(parentOf(x), );
                    setColor(leftOf(sib), );
                    rotateRight(parentOf(x));
                    x = ;
                }
            }
        }
        setColor(x);
    }
    private static final long serialVersionUID = 919286545866124006L;

    
Save the state of the TreeMap instance to a stream (i.e., serialize it).

SerialData:
The size of the TreeMap (the number of key-value mappings) is emitted (int), followed by the key (Object) and value (Object) for each key-value mapping represented by the TreeMap. The key-value mappings are emitted in key-order (as determined by the TreeMap's Comparator, or by the keys' natural ordering if the TreeMap has no Comparator).
    private void writeObject(java.io.ObjectOutputStream s)
        throws java.io.IOException {
        // Write out the Comparator and any hidden stuff
        s.defaultWriteObject();
        // Write out size (number of Mappings)
        s.writeInt();
        // Write out keys and values (alternating)
        for (Iterator<Map.Entry<K,V>> i = entrySet().iterator(); i.hasNext(); ) {
            Map.Entry<K,V> e = i.next();
            s.writeObject(e.getKey());
            s.writeObject(e.getValue());
        }
    }

    
Reconstitute the TreeMap instance from a stream (i.e., deserialize it).
    private void readObject(final java.io.ObjectInputStream s)
        throws java.io.IOExceptionClassNotFoundException {
        // Read in the Comparator and any hidden stuff
        s.defaultReadObject();
        // Read in size
        int size = s.readInt();
        buildFromSorted(sizenullsnull);
    }

    
Intended to be called only from TreeSet.readObject
    void readTreeSet(int sizejava.io.ObjectInputStream s, V defaultVal)
        throws java.io.IOExceptionClassNotFoundException {
        buildFromSorted(sizenullsdefaultVal);
    }

    
Intended to be called only from TreeSet.addAll
    void addAllForTreeSet(SortedSet<? extends K> set, V defaultVal) {
        try {
            buildFromSorted(set.size(), set.iterator(), nulldefaultVal);
        } catch (java.io.IOException cannotHappen) {
        } catch (ClassNotFoundException cannotHappen) {
        }
    }


    
Linear time tree building algorithm from sorted data. Can accept keys and/or values from iterator or stream. This leads to too many parameters, but seems better than alternatives. The four formats that this method accepts are: 1) An iterator of Map.Entries. (it != null, defaultVal == null). 2) An iterator of keys. (it != null, defaultVal != null). 3) A stream of alternating serialized keys and values. (it == null, defaultVal == null). 4) A stream of serialized keys. (it == null, defaultVal != null). It is assumed that the comparator of the TreeMap is already set prior to calling this method.

Parameters:
size the number of keys (or key-value pairs) to be read from the iterator or stream
it If non-null, new entries are created from entries or keys read from this iterator.
str If non-null, new entries are created from keys and possibly values read from this stream in serialized form. Exactly one of it and str should be non-null.
defaultVal if non-null, this default value is used for each value in the map. If null, each value is read from iterator or stream, as described above.
Throws:
IOException propagated from stream reads. This cannot occur if str is null.
java.lang.ClassNotFoundException propagated from readObject. This cannot occur if str is null.
    private void buildFromSorted(int sizeIterator it,
                                 java.io.ObjectInputStream str,
                                 V defaultVal)
        throws  java.io.IOExceptionClassNotFoundException {
        this. = size;
         = buildFromSorted(0, 0, size-1, computeRedLevel(size),
                               itstrdefaultVal);
    }

    
Recursive "helper method" that does the real work of the previous method. Identically named parameters have identical definitions. Additional parameters are documented below. It is assumed that the comparator and size fields of the TreeMap are already set prior to calling this method. (It ignores both fields.)

Parameters:
level the current level of tree. Initial call should be 0.
lo the first element index of this subtree. Initial should be 0.
hi the last element index of this subtree. Initial should be size-1.
redLevel the level at which nodes should be red. Must be equal to computeRedLevel for tree of this size.
    private final Entry<K,V> buildFromSorted(int levelint loint hi,
                                             int redLevel,
                                             Iterator it,
                                             java.io.ObjectInputStream str,
                                             V defaultVal)
        throws  java.io.IOExceptionClassNotFoundException {
        /*
         * Strategy: The root is the middlemost element. To get to it, we
         * have to first recursively construct the entire left subtree,
         * so as to grab all of its elements. We can then proceed with right
         * subtree.
         *
         * The lo and hi arguments are the minimum and maximum
         * indices to pull out of the iterator or stream for current subtree.
         * They are not actually indexed, we just proceed sequentially,
         * ensuring that items are extracted in corresponding order.
         */
        if (hi < loreturn null;
        int mid = (lo + hi) >>> 1;
        Entry<K,V> left  = null;
        if (lo < mid)
            left = buildFromSorted(level+1, lomid - 1, redLevel,
                                   itstrdefaultVal);
        // extract key and/or value from iterator or stream
        K key;
        V value;
        if (it != null) {
            if (defaultVal==null) {
                Map.Entry<K,V> entry = (Map.Entry<K,V>)it.next();
                key = entry.getKey();
                value = entry.getValue();
            } else {
                key = (K)it.next();
                value = defaultVal;
            }
        } else { // use stream
            key = (K) str.readObject();
            value = (defaultVal != null ? defaultVal : (V) str.readObject());
        }
        Entry<K,V> middle =  new Entry<K,V>(keyvaluenull);
        // color nodes in non-full bottommost level red
        if (level == redLevel)
            middle.color = ;
        if (left != null) {
            middle.left = left;
            left.parent = middle;
        }
        if (mid < hi) {
            Entry<K,V> right = buildFromSorted(level+1, mid+1, hiredLevel,
                                               itstrdefaultVal);
            middle.right = right;
            right.parent = middle;
        }
        return middle;
    }

    
Find the level down to which to assign all nodes BLACK. This is the last `full' level of the complete binary tree produced by buildTree. The remaining nodes are colored RED. (This makes a `nice' set of color assignments wrt future insertions.) This level number is computed by finding the number of splits needed to reach the zeroeth node. (The answer is ~lg(N), but in any case must be computed by same quick O(lg(N)) loop.)
    private static int computeRedLevel(int sz) {
        int level = 0;
        for (int m = sz - 1; m >= 0; m = m / 2 - 1)
            level++;
        return level;
    }
New to GrepCode? Check out our FAQ X