zoukankan      html  css  js  c++  java
  • java之==操作符和equals操作符

    ==操作符:

    • 基本数据类型比较值;
    • 引用数据类型比较引用(是否指向同一个对象)

    equals操作符:

    • 引用数据类型比较引用(是否指向同一个对象)
    • 对于String、File、Date、包装类来说,只比较类型和内容,而不考虑引用的是否是同一个对象,因为这些类中重写了equals方法。
    public class Main {
    
        
        public static void main(String[] args) {
            Person p1 = new Person();
            Person p2 = new Person();
            System.out.println(p1.equals(p2));
            System.out.println(p1==p2);
        }
    }

    输出:

    false

    false

    public class Main {
    
        
        public static void main(String[] args) {
            Person p1 = new Person();
            Person p2 = p1;
            System.out.println(p1.equals(p2));
            System.out.println(p1==p2);
        }
    }

    输出:

    true

    true

    public class Main {
    
        
        public static void main(String[] args) {
            String a1 = "hello";
            String b1 = "hello";
            System.out.println(a1.equals(b1));
            System.out.println(a1==b1);
            String a2 = new String("hello");
            String b2 = new String("hello");
            System.out.println(a2.equals(b2));
            System.out.println(a2==b2);
        }
    }

    输出:

    true

    true

    true

    false

    说明:a1和b1指向的是同一个String,而a2和b2指向不同的String,所以a2.equals(b2)只比较值返回true,==比较引用返回false。

  • 相关阅读:
    170929-关于md5加密
    170911-关于maven的知识点
    opencv-python 学习初探1
    使用PDFminer3k解析pdf为文字遇到:WARING:root:GBK-EUC-H
    Python time strptime()与time strftime()
    chromedriver下载安装
    计数
    高效的几个小技巧
    phantomjs在win10下的安装
    win10下安装lxml
  • 原文地址:https://www.cnblogs.com/xiximayou/p/12049647.html
Copyright © 2011-2022 走看看