java 的==和equals的区别(二)

java 的==和equals的区别

java 的==和equals的区别

==通常表明引用的是同一个东西(引用的地址相同),equals通常表明两个对象的内容相同值相同

-------------------------------------------------------------------------------------------------------------------------------------

11111)对于==,如果作用于基本数据类型的变量,则直接比较其存储的 “”是否相等;

  int n=3;
  int m=3;
  System.out.println(n==m); // true

  如果作用于引用类型的变量,则比较的是所指向的对象的地址

        String str = new String("hello");
        String str1 = new String("hello");
        String str2 = new String("hello");
        
        System.out.println(str1==str2); // false 因为这两个对象是先后new的,地址肯定不相等
        
        str3 = str;
        str4 = str;
        System.out.println(str3==str4); // true  虽然应用不一样,但是指向的是同一个new的对象/地址

22222)对于equals方法,注意:equals方法不能作用于基本数据类型的变量!!!!!

    如果没有对equals方法进行重写,则比较的是引用类型的变量所指向的对象的地址;(与==效果一样)

class Cat {
    int color, weight, height;
    public Cat(int color, int weight, int height) {
        this.color = color;
this.weight = weight; this.height = height; } }
         Cat c1 = new Cat(1, 1, 1);
         Cat c2 = new Cat(1, 1, 1);
         System.out.println("c1==c2的结果是:"+(c1==c2));//false 因为 == 对引用类型/对象做比较的时候,比较的是“地址”,对基本数据类型比较的是“值”
         System.out.println("c1.equals(c2)的结果是:"+c1.equals(c2));//false 此时没有对equals重写,则equals(还是object类的)与“==”效果一样比较地址
如果对equals进行重写之后就比较的是对象内容了,下面是重写equals的代码
public boolean equals(Object obj){
        if (obj==null){
            return false;
        }
        else{
            if (obj instanceof Cat){
                Cat c = (Cat)obj;
                if (c.color==this.color && c.weight==this.weight && c.height==this.height){
                    return true;
                }
            }
        }
        return false;
    }

    诸如String、Date等类对equals方法进行了重写的话,比较的是所指向的对象的内容

           Double,Date,Integer等,都对equals方法进行了重写用来比较指向的对象所存储的内容是否相等。

        String str1 = new String("hello");
        String str2 = new String("hello");
        
        System.out.println(str1.equals(str2)); // true 对equals方法进行重写,对比字符串的每一个字符都相等
原文地址:https://www.cnblogs.com/111testing/p/6771212.html