欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

认识Map中的TreeMap

程序员文章站 2022-03-06 11:26:02
...
TreeMap是map接口的一个实现,TreeMap中的key是排好序的,这是TreeMap和HashMap最大的区别。
package test;   
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);   
         }   
  
  
}  


输出:
The following is HashMap
{002=20, 004=40, 001=10, 003=30}
The following is TreeMap
{001=10, 002=20, 003=30, 004=40}
相关标签: Java