java容器的相关问题

什么时候需要重写容器类的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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值