博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Java中判断Integer类型的值是否相等
阅读量:4093 次
发布时间:2019-05-25

本文共 1502 字,大约阅读时间需要 5 分钟。

例子

public class Demo {	public static void main(String[] args) {		Integer c = -128;		Integer d = -128;		System.out.println("c == d: " + (c == d));		System.out.println("c.equals(d): " + c.equals(d));		System.out.println("c.intValue() == d.intValue(): " + (c.intValue() == d.intValue()));		System.out.println("Objects.equals(c, d): " + Objects.equals(c, d));				Integer e = 127;		Integer f = 127;		System.out.println("e == f: " + (e == f));		System.out.println("e.equals(f): " + e.equals(f));		System.out.println("e.intValue() == f.intValue(): " + (e.intValue() == f.intValue()));		System.out.println("Objects.equals(e, f): " + Objects.equals(e, f));				Integer g = 128;		Integer h = 128;		System.out.println("g == h: " + (g == h));		System.out.println("g.equals(h): " + g.equals(h));		System.out.println("g.intValue() == h.intValue():" + (g.intValue() == h.intValue()));		System.out.println("Objects.equals(g, h): " + Objects.equals(g, h));	}}

运行结果:

c == d: truec.equals(d): truec.intValue() == d.intValue(): trueObjects.equals(c, d): truee == f: truee.equals(f): truee.intValue() == f.intValue(): trueObjects.equals(e, f): trueg == h: falseg.equals(h): trueg.intValue() == h.intValue():trueObjects.equals(g, h): true

解释

  1. 当用“==”进行比较时,jvm默认是比较数据在java堆的地址;用equals()是比较对象的值
  2. 当数值在-128~127之间时,jvm会自动将Integer转成int数值进行比较,超过这个范围会按Integer对象来比较
  3. ==是一个关系运算符,如果比较的两端都为基本数据类型,则判断两者的值是否相等,(判断过程中还有不同基本类型的转化,这里不做讨论);如果比较的两端都为引用类型的话,则比较两者所指向对象的地址是否相同;对于equals方法,如果对象所在的类重写了equals方法,则按照重写的方法进行比较,如果没有,则比较两者所指向对象的地址是否相同

参考博客:

转载地址:http://eqtii.baihongyu.com/

你可能感兴趣的文章
DirectX11 三种光照组成对比
查看>>
DirectX11 指定材质
查看>>
DirectX11 平行光
查看>>
DirectX11 点光
查看>>
DirectX11 聚光灯
查看>>
DirectX11 HLSL打包(packing)格式和“pad”变量的必要性
查看>>
DirectX11 光照演示示例Demo
查看>>
漫谈一下前端的可视化技术
查看>>
VUe+webpack构建单页router应用(一)
查看>>
Vue+webpack构建单页router应用(二)
查看>>
从头开始讲Node.js——异步与事件驱动
查看>>
Node.js-模块和包
查看>>
Node.js核心模块
查看>>
express的应用
查看>>
NodeJS开发指南——mongoDB、Session
查看>>
Express: Can’t set headers after they are sent.
查看>>
2017年,这一次我们不聊技术
查看>>
实现接口创建线程
查看>>
Java对象序列化与反序列化(1)
查看>>
HTML5的表单验证实例
查看>>