==和equals的比较

  一 : == 的特点: 

    a == b ;

      1.如果A和B是基本数据类型    ==   比较的是两个变量的值

      2.如果A和B是引用数据类型    == 比较的是两个变量的内存地址

  二:重写的equals方法

    Object中的equals方法:比较的是内存地址

    public boolean equals(Object obj) {
        return (this == obj);
    }

    String类中重写的equals 方法:比较的是内容;

    public boolean equals(Object anObject) {
        if (this == anObject) {
            return true;
        }
        if (anObject instanceof String) {
            String anotherString = (String) anObject;
            int n = value.length;
            if (n == anotherString.value.length) {
                char v1[] = value;
                char v2[] = anotherString.value;
                int i = 0;
                while (n-- != 0) {
                    if (v1[i] != v2[i])
                            return false;
                    i++;
                }
                return true;
            }
        }
        return false;
    }

实例:观察String中的equals方法

   String a = "abc";
   String b = "abc";
   String c = new String("abc");

   System.out.println(a.equals(b)); // 值肯定一致 所有返回 true
   System.out.println(a == b);// 内存地址也一致 所以 true
 
   System.out.println(a.equals(c));// 值肯定一致 所有返回 true
   System.out.println(a == c);// 内存地址不一致 所以 false

实例:观察String类型的比较

   String a = "a";
   String b = "b";
   String c = "ab";
   System.out.println(c == (a+b));//false
   //01.a 和 b 都是变量,在编译期间无法确定变量的值;
   //02.c在编译期间已经确定,ab无法确定;

  三:关键字 final

    1.final可以修饰  类,属性 ,方法

    2.被final修饰的类,不能被继承;

      final修饰的方法,不能被子类重写;

      final修饰的属性,运行期间不能改变;

实例:观察常量的比较

   final String a = "a";
   final String b = "b";
   String c = "ab";
   System.out.println(c==(a+b));//true

实例:以Student为例重写equals方法 

    public boolean equals(Object anObject) {
        if (anObject == null) {
            return false;
        }
        if (this == anObject) {
            return true;
        }
        if (!(anObject instanceof Person)) {
            return false;
        }
        Student per = (Student) anObject;
        return this.age == per.age && this.name == per.name;
    }
原文地址:https://www.cnblogs.com/ak666/p/8010842.html