1 |
dl |
1.2 |
/* |
2 |
|
|
* Written by Doug Lea with assistance from members of JCP JSR-166 |
3 |
|
|
* Expert Group and released to the public domain, as explained at |
4 |
|
|
* http://creativecommons.org/licenses/publicdomain |
5 |
|
|
*/ |
6 |
|
|
|
7 |
|
|
// Adapted from bug report 5018354 |
8 |
dl |
1.1 |
import java.util.*; |
9 |
|
|
|
10 |
|
|
public class LastKeyOfSubMap { |
11 |
|
|
private static final Comparator NULL_AT_END = new Comparator() { |
12 |
|
|
/** |
13 |
|
|
* Allows for nulls. Null is greater than anything non-null. |
14 |
|
|
*/ |
15 |
|
|
public int compare(Object pObj1, Object pObj2) { |
16 |
|
|
if (pObj1 == null && pObj2 == null) return 0; |
17 |
|
|
if (pObj1 == null && pObj2 != null) return 1; |
18 |
|
|
if (pObj1 != null && pObj2 == null) return -1; |
19 |
|
|
return ((Comparable) pObj1).compareTo(pObj2); |
20 |
|
|
} |
21 |
jsr166 |
1.3 |
}; |
22 |
dl |
1.1 |
|
23 |
|
|
|
24 |
|
|
public static void main(String[] pArgs) { |
25 |
|
|
SortedMap m1 = new TreeMap(NULL_AT_END); |
26 |
|
|
m1.put("a", "a"); |
27 |
|
|
m1.put("b", "b"); |
28 |
|
|
m1.put("c", "c"); |
29 |
|
|
m1.put(null, "d"); |
30 |
|
|
|
31 |
|
|
SortedMap m2 = new TreeMap(m1); |
32 |
|
|
|
33 |
|
|
System.out.println(m1.lastKey()); |
34 |
|
|
System.out.println(m1.get(m1.lastKey())); |
35 |
|
|
Object m1lk = m1.remove(m1.lastKey()); |
36 |
|
|
if (m1lk == null) |
37 |
|
|
throw new Error("bad remove of last key"); |
38 |
|
|
|
39 |
|
|
m2 = m2.tailMap("b"); |
40 |
|
|
|
41 |
|
|
System.out.println(m2.lastKey()); |
42 |
|
|
System.out.println(m2.get(m2.lastKey())); |
43 |
|
|
Object m2lk = m2.remove(m2.lastKey()); |
44 |
|
|
if (m2lk == null) |
45 |
|
|
throw new Error("bad remove of last key"); |
46 |
|
|
} |
47 |
|
|
} |