【java的自动打包和解包】

map接口中的put(k,v)方法中的v参数要求的是对象的,其一般用法:

  import java.util.*;

  public class TestMap {

  public static void main(String args[]) {

  Map m1 = new HashMap();

  m1.put("one",new Integer(1));//v参数是整形对象对象

  m1.put("two",new Integer(2));

  m1.put("three",new Integer(3));

  System.out.println(m1);

  if(m1.containsKey("two")) {

  int i = ((Integer)m1.get("two"))。intValue();//强制转换为整形对象在得出值

  System.out.println(i);

  }

  }

  }

  利用自动打包和解包就很方便了:

  import java.util.*;

  public class TestMap {

  public static void main(String args[]) {

  Map m1 = new HashMap();

  m1.put("one", 1);//自动打包,注意与上面代码的区别

  m1.put("two", 2);

  m1.put("three", 3);

  System.out.println(m1)

  if(m1.containsKey("two")) {

  int i = (Integer)m1.get("two");//自动解包

  System.out.println(i);

  }

  }

  }

  题外话:强制转换的存在,导致了泛型的出现。

posted @ 2013-09-27 09:34  豆豆逗逗  阅读(183)  评论(0编辑  收藏  举报