zoukankan      html  css  js  c++  java
  • ==和equals的区别

    1. ==为关系运算符,其作用是r检查如果两个操作数的值是否相等,如果相等则条件为真。

      1.1 对于基本数据类型(byte,short,int,long,char,boolean,float,double),比较的是具体的数值。

      1.2 对于引用数据类型(对象,数组),比较的是他们在内存中的地址。

            int a = 5;
            int b = 5;
            System.out.println(a == b);//结果为true
            
            Student s1 = new Student();
            Student s2 = new Student();
            System.out.println(s1 == s2);//结果为false       

    2. equals是超类object具有的方法,因此所有的引用类型都具有这个方法。用来检测两个对象是否相等

      .2.1 equals()方法默认比较的是对象的内存地址,和==功能一样。

            Student s1 = new Student();
            Student s2 = new Student();
            //结果和 == 关系运算符一样,都为false
            System.out.println(s1.equals(s2));        

      2.2 如果重写该方法,一般是比较对象的属性值

            //equals方法的源代码
            public boolean equals(Object obj) {
                return (this == obj);
            }    

    3. 重写equals方法

      3.1 student类

    public class Student {
    
        private int age;
    
        @Override
        public boolean equals(Object o) {
            if (this == o) 
                return true;
            //判断传入的对象是否为Student类的一个实例化对象
            if (!(o instanceof Student))
                return false;
            Student student = (Student) o;
            return (this.age == student.age);
        }
    }

      3.2 EqualsTest类

    public class EqualsTest {
        
        public static void main(String[] args) {
            
            Student s1 = new Student();
            Student s2 = new Student();
            System.out.println(s1 == s2);//结果为false
            System.out.println(s1.equals(s2));//结果为true
            
        }
    }
  • 相关阅读:
    TODO supply a title
    three.js ---- 3d页面开发入门
    ProgressBar.Style ---- Marquee
    C#中的Task.Delay()延迟与异步执行返回结果
    位运算-实现加减乘除
    2020年专项附加扣除信息,个税纳税记录查询
    C#动态执行JS和VBS脚本
    windows下bat批处理实现守护进程(有日志)
    C#创建快捷方式的两种方法
    C#中创建程序的快捷方式
  • 原文地址:https://www.cnblogs.com/Code-Handling/p/13139241.html
Copyright © 2011-2022 走看看