==和equals的比较 2020-03-05 14:58 **==比较前后两个变量里面装的东西;而equals()是一个方法,用户可以自定义比较内容和规则。**所以这两者根本就不应该做比较。只是因为其“含义”或者说“作用”有了重合的地方,所以经常拿来做比较。(从底层来说==作为操作符也是可以重载的,但是它不是像equals()一样经常被用户自定义改动) 对于基本变量和引用变量,==比较所展现的效果是不同的,其原因在于基本变量和引用变量里面储存的内容不同,而不是因为==作用在不同变量上。即:和==无关,==一直都是比较前后两个变量里面装的东西;效果的不同是由于比较者不同引起的。 ### 引用类型 ```java public class Main { public static void main(String[] args) { String c1 = new String("abc"); String c2 = new String("abc"); String c3 = c1; String d1 = "abc"; String d2 = "abc"; System.out.println("c1 == c2的运算结果为" + (c1 == c2));//false 不同对象 System.out.println("c2 == c3的运算结果为:" + (c2 == c3));//false System.out.println("c1 == c3的运算结果为: " + (c1==c3));//true System.out.println("c2.equals(c3)的运算结果为:" + c2.equals(c3));//true String类重写了equals方法:比较字符串序列是否相同 System.out.println("d1 == d2的运算结果为:" + (d1 == d2));//true System.out.println("c1 == d1的运算结果为:" + (c1 == d1));//false System.out.println("c1.equals(d1)的运算结果为:" + c1.equals(d1));//true } } ``` ![](https://minio.riun.xyz/riun1/2022-06-25_pRk2v9lMnLY1JxEkOB.png) ### 涉及到普通类型时的== 1、new出的对象比较,都是不同的 2、数字赋值给引用对象,得看数字的范围 3、和int比较时,都会被“同化”为比较数字的值 ```java package com.example.demo.Algorithm; /** * @author: HanXu * on 2021/8/27 * Class description: Integer比较 */ public class Demo7 { public static void main(String[] args) { //---------------------------------------第一组对照试验:new出的Integer 只要是new的就不相同 //只要是new的对象,比较起来不同对象永远不同 /*Integer i1 = new Integer(1); Integer i2 = new Integer(1); System.out.println(i1 == i2); //false */ /*Integer i1 = new Integer(3000); Integer i2 = new Integer(3000); System.out.println(i1 == i2); //false */ /*Integer i1 = 1; Integer i2 = new Integer(1); System.out.println(i1 == i2); //false */ //---------------------------------------第二组对照试验:直接将数字赋值给Integer,结果要看数字的大小 //当不是new的对象时,如果赋值的数字是[-128,127]这256个整数,那么会在缓冲区中,赋值时是直接去拿的这个数字,所以[-128,127]内比较是true; /*Integer i1 = -128; Integer i2 = -128; System.out.println(i1 == i2); //true */ /*Integer i1 = 0; Integer i2 = 0; System.out.println(i1 == i2); //true */ /*Integer i1 = 127; Integer i2 = 127; System.out.println(i1 == i2); //true */ //超过这个整数范围时,缓存区没有了,就要去new了,所以看起里是Integer i1 = 128;其实是Integer i1 = new Integer(128); 两个对象比较就是false /*Integer i1 = 128; Integer i2 = 128; System.out.println(i1 == i2); //false */ /*Integer i1 = -129; Integer i2 = -129; System.out.println(i1 == i2); //false */ //---------------------------------------第三组对照试验:和int比较时,只比较值,相同的==结果永远相同 /*int i1 = 1; Integer i2 = 1; System.out.println(i1 == i2); //true */ /*int i1 = 1; Integer i2 = new Integer(1); System.out.println(i1 == i2); //true */ /*int i1 = 3000; Integer i2 = new Integer(3000); System.out.println(i1 == i2); //true */ } } ``` --END--
发表评论