• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

简单了解java中int和Integer的区别

java 搞代码 4年前 (2022-01-05) 76次浏览 已收录 0个评论

这篇文章主要介绍了简单了解java中int和Integer的区别,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

这篇文章主要介绍了简单了解java中int和Integer的区别,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

1、Integer是int的包装类,int则是java的一种基本数据类型

2、Integer变量必须实例化(new 一下是最常见的实例化)后才能使用,而int变量不需要

3、Integer实际是对象的引用,new Integer(),实际上是生成一个指针指向此对象;而int则是直接存储数据值

4、Integer的默认值是null,int的默认值是0

注意

Integer对象会占用更多的内存。Integer是一个对象,需要存储对象的元数据。但是int是一个原始类型的数据,所以占用的空间更少

关于Integer和int的比较

1. 两个new实例化出来的Integer变量比较,结果为false.

 /** * @author tracydzf *比较两个new出来的Integer * */ public class Test { public static void main(String[] args) { Integer a = new Integer(100); Integer b = new Integer(100); System.out.println(a==b); //输出false } }

当new一个Integer时,实际上是生成一个指针,指向此对象,两次new Integer生成的是两个对象,对象储存在堆当中,其内存地址不同,所以两个new出来的Integer变量不等。

2.int 和Integer在进行比较的时候,Integer会进行拆箱,转为int值与int进行比较

 /** * @author tracydzf *int 和 Integer的比较 * */ p<em style="color:transparent">来源gao.dai.ma.com搞@代*码网</em>ublic class Test { public static void main(String[] args) { Integer a = new Integer(100); int b = 100; System.out.print(a == b); //true } }

3.非new生成的Integer变量和new Integer()生成的变量比较时,结果为false。(因为非new生成的Integer变量指向的是java常量池中的对象,而new Integer()生成的变量指向堆中新建的对象,两者在内存中的地址不同)

 /** * @author tracydzf * Integer 和 new Integer的比较 * */ public class Test { public static void main(String[] args) { Integer a = new Integer(100); Integer b = 100; System.out.print(a == b); //false } }

4.对于两个非new生成的Integer对象,进行比较时.

注意:

① java在编译Integer i = 100 ;时,会翻译成为Integer i = Integer.valueOf(100),java API中对Integer类型的valueOf的定义如下:

 public static Integer valueOf(int i){ assert IntegerCache.high >= 127; if (i >= IntegerCache.low && i <= IntegerCache.high){ return IntegerCache.cache[i + (-IntegerCache.low)]; } return new Integer(i); }

② 当自动装箱后生成的Integer的对象,其值 -128<= x <= 127 时,这个对象会直接取缓存IntegerCache中的对应的对象,生成的当然也是个对象。

我们来看看例子

这里a跟b都是128,不会再IntegerCache取缓存对象,所以是false.

 /** * @author tracydzf * Integer 和 Integer的比较 * */ public class Test { public static void main(String[] args) { Integer a = 128; Integer b = 128; System.out.print(a == b); //false } }

a,b都是127,数值相等,且满足在IntegerCache取缓存的条件,所以对象相等.

 /** * @author tracydzf * Integer 和 Integer的比较 * */ public class Test { public static void main(String[] args) { Integer a = 127; Integer b = 127; System.out.print(a == b); //true } }

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持gaodaima搞代码网

以上就是简单了解java中int和Integer的区别的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:简单了解java中int和Integer的区别

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址