幻境
We are extremely fortunate not to know precisely the kind of world we live in
posts - 22,comments - 39,trackbacks - 0

 

原生类型的autoboxingauto-unboxing

我们知道,在Java中,int,long等原生类型不是一个继承自Object的类,所以相应的,有很多操作我们都不能利用原生类型操作,比如想要把一个整数放入到一个集合中,我们必须首先创建一个Integer对象,然后再将这个对象放入到集合中。当我们从集合中取数的时候,取出来的是一个Integer对象,因此不能直接对它使用加减乘除等运算符,而是必须用Integer.intValue()取到相应的值才可以,这样的过程称之为boxingunboxing

J2SE5.0支持autoboxingauto-unboxing,也就是说我们以后不需要再手动地做这些boxingunboxing操作了,java语言会替我们完成。具体可以参照下面的示例:

List<Integer> intList=new ArrayList<Integer>();

intList.add(2);

intList.add(new Integer(5));

int i=3+intList.get(0);//i=5

int j=3+intList.get(1); //j=8

 

从这一段程序中我们可以看到,autoboxingauto-unboxing为我们省掉了很多不必要的工作。

posted on 2005-05-12 10:57 阅读(1167) 评论(1)  编辑  收藏 所属分类: 编程相关

FeedBack:
# re: J2SE5.0新特性示例---原生类型的autoboxing和auto-unboxing
2006-07-28 15:35 | jclue
say if I add another int to the intList like

intList.add(3); // index 2

now we have {2 ,5 ,3} in the intList

what happen if do intList.remove (2) ???
would the 3 (index 2) be removed or 2 (index 0)?
  回复  更多评论
  

只有注册用户登录后才能发表评论。


网站导航: