如何选择数据结构及Map接口

来源:互联网 发布:人工智能带来的便利 编辑:程序博客网 时间:2024/06/11 20:53
数据结构 效率 Array 读快改慢 Linked 改快读慢 Hash 两者之间

Map接口

  • 实现Map接口的类用来存储 键-值(key - value)
  • 实现类有HashMap和TreeMap(二叉树)
  • 键-值对通过键来标识,所以键值不能重复(equals+hashcode)

Map 方法举例

package TestCollections;import java.util.*;public class TestMap {        public static void main(String args[]){            Map m1 = new HashMap(); Map m2 = new TreeMap();            m1.put("one" ,new Integer(1));            //m1.put("one" ,1);支持自动打包和解包,这种写法有效            m1.put("two" ,new Integer(2));            m1.put("three" ,new Integer(3));            m2.put("A" ,new Integer(1));            m2.put("B" ,new Integer(2));            System.out.println(m1.size());            System.out.println(m1.containsKey("one"));            System.out.println                (m2.containsValue(new Integer(1)));            if(m1.containsKey("two")){                int i = ((Integer)m1.get("two")).intValue();//get返回的是Object类型,所以需要转换                //itn i = (Integer)m1.get("two");自动解包,写法有效                System.out.println(i);            }            Map m3 = new HashMap(m1);            m3.putAll(m2);            System.out.println(m3);        }    }

结果:

3truetrue2{A=1, B=2, two=2, three=3, one=1}

自动打包和解包__Auto-boxing/unboxing

自动把基础类型的值转化为对象,反之亦然;见上例的注释

原创粉丝点击