String 和Integer中 == 和 equals的使用
来源:互联网 发布:全国中小学名录数据库 编辑:程序博客网 时间:2024/06/13 00:43
equals的作用:用于判断两个变量是否是对同一个对象的引用,即堆中的内容是否相同,返回值为布尔类型
“==”操作符的作用:
1、用于基本数据类型的比较
2、判断引用是否指向堆内存的同一块地址。
public static void main(String[] args){ String a = "Hello"; String b = "Hello"; String c = new String("Hello"); String d = new String("Hello"); /**String作为一个基本类型来使用**/ System.out.println(a==b);//ture System.out.println(a.equals(b));//true System.out.println(a==c); //false System.out.println(a.equals(c)); //true /**String作为引用类型来使用**/ System.out.println(c == d); //引用不同,false System.out.println(c.equals(d)); //内容相同,true }
public static void main(String[] args) { Integer a = 150; Integer b = 150; Integer c = new Integer(150); Integer d = new Integer(150); int e = 150; System.out.println(a==b); //false System.out.println(a.equals(b));//true System.out.println(a==c);//false System.out.println(a.equals(c));//true System.out.println(c==d);//false System.out.println(c.equals(d));//true //因为与初始化值做比较的时候,会将封装类型进行拆箱操作,转换为基本类型。这里比较的就是基本类型的值了* System.out.println(a==e);//true System.out.println(a.equals(e));//true System.out.println(c==e);//true System.out.println(c.equals(e));//true }
public int intValue() { return value;}
其中有个特例:
public static void test(){ Integer a=1; Integer b=1; System.out.println(a==b); //true System.out.println(a.equals(b));//true }
Integer a=150;//会将int类型通过valueof转换成Integer类型。下面是valueof源码。static final int low = -128; public static Integer valueOf(int i) { if (i >= IntegerCache.low && i <= IntegerCache.high) return IntegerCache.cache[i + (-IntegerCache.low)]; return new Integer(i); }
也就是说在-128到127之间的值会缓存到IntegerCache.cache中,所以在Integer x=在-128到127之间时,返回的是同一个对象,所以出现了上文的情况。(如果换成 >、>=、<、<=会出现什么情况呢?这中情况会自动拆箱比较值。)
阅读全文
0 0
- String 和Integer中 == 和 equals的使用
- java中String 的==和equals;String直接赋值和使用new String()
- 关于Integer类中equals和"=="的区别
- ==和equals方法的区别以及Integer和String的应用
- Integer == 和equals的区别
- Integer String 的equals == 区别
- @在String中==和equals的区别
- Java中String的equals和==
- String中"equals"和"=="的区别
- String中“==”和equals的区别
- JAVA中String的“==”和equals()浅析
- java中String的equals和==
- Java中String的==和equals区别
- java:String使用equals和==比较的区别
- java:String使用equals和==比较的区别
- java:String使用equals和==比较的区别
- java:String使用equals和==比较的区别
- java:String使用equals和==比较的区别
- Linux系统命令行基本操作(一)
- 关于Android屏幕适配的一些细节
- Java Web:从Servlet开始
- HTTP-8种请求方式
- docker save与docker export的区别
- String 和Integer中 == 和 equals的使用
- Fragment 生命周期的详情
- 使用Docker搭建SonarQube检测代码质量
- 机器学习常见的矩阵求导总结
- git命令
- 82. 落单的数
- 白话Spring
- 传感器融合
- android 连按两次Back键退出 (单Activity多Fragment,保留根Fragment)