什么时候需要重写容器类的hashcode()和 equals()方法?
当容器类对象作为索引时需要重写这两个方法。 多用于 HashSet、HashMap 以及HashTree类。
因为在哈希表中当需要比较索引值是否equals时需要重写equals方法,而如果两个对象equals,那么他们的hashcode也必须相同; 反之,如果两个对象hashcode相同,但不equals,在具有相同hashcode的对象中再进行遍历复杂度就小很多了。
HashMap 和TreeMap的区别:
import java.util.HashMap;
import java.util.TreeMap;
public class TestTreeMap {
/**
* @param args
*/
public static void main(String[] args) {
//HashMap是无序的
prt("The following is HashMap");
HashMap<String,Object> hashMap = new HashMap<String,Object>();
hashMap.put("004", new Integer(40));
hashMap.put("003", new Integer(30));
hashMap.put("001", new Integer(10));
hashMap.put("002", new Integer(20));
prt(hashMap);
//TreeMap是有序的
prt("The following is TreeMap");
TreeMap<String,Object> treeMap = new TreeMap<String,Object>();
treeMap.put("004", new Integer(40));
treeMap.put("003", new Integer(30));
treeMap.put("001", new Integer(10));
treeMap.put("002", new Integer(20));
prt(treeMap);
}
private static void prt(Object obj) {
System.out.println(obj);
}
}
HashMap的访问:
import java.util.*;
public class VisitHashMap{
public static void main(String[] args){
Map<String,Integer> m=new HashMap<String,Integer>();
m.put("1",11);
m.put("2",22);
m.put("3",33);
Iterator it=m.entrySet().iterator();
while(it.hasNext()){
Map.Entry e=(Map.Entry)it.next();
System.out.println(e.getKey());
System.out.println(e.getValue());
}
}
}
更多关于java 容器的分析:http://lorry1113.iteye.com/category/64948?show_full=true