SortedMap的实现类TreeMap可以实现元素排序,其底层结构为红黑树。利用compareTo()方法来比较元素key大小,判断其是否相等。若使用自定义的类作为key值,则应该保证重写的equals()与compareTo()返回结果一致。
class R implements Comparable {
int count;
public R(int count) {
this.count = count;
}
public String toString() {
return "R[count" + count + "]";
}
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj != null && obj.getClass() == R.class) {
R r = (R) obj;
return r.count == this.count;
}
return false;
}
@Override
public int compareTo(Object obj) {
R r = (R) obj;
return count > r.count ? 1 : count < r.count ? -1 : 0;
}
}
public class TreeMapTest {
public static void main(String[] args) {
TreeMap tm = new TreeMap();
tm.put(new R(3), "莫欺少年穷");
tm.put(new R(-5), "天下何人不识君");
tm.put(new R(9), "朋友一生一起走");
// {R[count-5]=天下何人不识君, R[count3]=莫欺少年穷, R[count9]=朋友一生一起走}
System.out.println(tm);
System.out.println(tm.lastKey());
// 比2大的最小key值
System.out.println(tm.higherKey(new R(2)));
//{R[count3]=莫欺少年穷}
System.out.println(tm.subMap(new R(-1), new R(4)));
}
}WeakHashMap类的key为弱引用,当垃圾回收了该key所对应的实际对象后,WeakHashMap会删除对应的key-value对。
public class WeakHashMapTest {
public static void main(String[] args) {
WeakHashMap whm = new WeakHashMap();
//key为匿名字符串对象
whm.put(new String("语文"), new String("良好"));
whm.put(new String("数学"), new String("优秀"));
whm.put(new String("英语"), new String("中"));
//key为字符串直接量,系统会自动保留其强引用
whm.put("java", new String("中等"));
// {java=中等, 数学=优秀, 英语=中, 语文=良好}
System.out.println(whm);
System.gc();
System.runFinalization();
//通常情况下,结果为{java=中等}
System.out.println(whm);
}
}
京公网安备 11010502036488号