Collection和Map中元素的存储顺序

来源:互联网 发布:ac尼尔森数据 奶 2015 编辑:程序博客网 时间:2024/06/08 12:42

Java容器类库中两种主要的类型:Collection和Map。Collection只保存一个元素;Map保存两个元素,即键和与之相关的值。

Collection

                  List 【允许元素重复,输出顺序与插入顺序一致】

                           ArrayList 【随机访问元素性能优于LinkedList】

                           LinkedList【进行频繁的增删操作时性能优于ArrayList】

                  Set【不允许元素重复】

                          HashSet【最快的获取元素】

                          TreeSet【按照比较结果的升序保存对象】

                           LinkedHashSet【按照添加的顺序保存对象】

Map【不允许键重复】

               HashMap【提供最快的查找技术】

               TreeMap 【按照比较结果的升序保存键】

               LinkedHashMap【按照插入顺序保存键】

参考<Java编程思想>的测试程序:

测试结果:

源码: 

           

package com.interview;import java.util.*;public class ColStorage { static Collection fill(Collection<String> collection){        collection.add("rat");        collection.add("cat");        collection.add("dog");        collection.add("dog");return collection;}    static Map fill(Map<String,String> map){    map.put("rat", "Fuzzy");    map.put("cat", "Rags");    map.put("dog", "Boscos");    map.put("dog", "Spot");    return map;    } /** * @两种主要容器的存储顺序 * @author wx * @date 2016/04/15 */public static void main(String[] args) {System.out.println("ArrayList:    "+fill(new ArrayList<String>()));System.out.println("LinkedList:   "+fill(new LinkedList<String>()));System.out.println("HashSet:      "+fill(new HashSet<String>()));System.out.println("TreeSet:      "+fill(new TreeSet<String>()));System.out.println("LinkedHashSet:"+fill(new LinkedHashSet<String>()));System.out.println("HashMap:      "+fill(new HashMap<String,String>()));System.out.println("TreeMap:      "+fill(new TreeMap<String,String>()));System.out.println("LinkedHashMap:"+fill(new LinkedHashMap<String,String>()));}}

                        

0 0
原创粉丝点击