日期:2014-05-20 浏览次数:20870 次
tree.put(new TreeElement(123, "aii"), 123);
//这是remove失败的情况
tree.remove(new TreeElement(123, "aii"));
//这是我的比较器写法:
@Override
public int compare (TreeElement o1, TreeElement o2) {
System.out.println("--->"+o1.value+"; "+o2.value);
if(o1.value > o2.value) {
return -1;
}
else if(o1.value == o2.value && o1.name.equals(o2.name)) {
// 这里进行返回0的操作非常重要,否则无法remove和containsKey
return 0;
}
else {
return 1;
}
}
import java.util.Comparator;
import java.util.TreeMap;
public class TestTreeMap {
public static void main(String[] args) {
TreeMap<TreeElement, Integer> m = new TreeMap<TreeElement, Integer>(new Comparator<TreeElement>() {
public int compare (TreeElement o1, TreeElement o2) {
System.out.println("--->"+o1.value+"; "+o2.value);
if(o1.value > o2.value) {
return -1;
}
else if(o1.value == o2.value && o1.name.equals(o2.name)) {
return 0;
}
else {
return 1;
}
}
});
m.put(new TreeElement(123, "aii"), 123);
System.out.println("after add:" + m.size());
TreeElement k = new TreeElement(123, "aii");
System.out.println("get:" + m.get(k));
m.remove(k);
System.out.println("after remove:" + m.size());
}
}
class TreeElement {
public int value;
public String name;
public TreeElement(int value, String name) {