• ==和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
            
        }
    }
  • 相关阅读:
    VSTO开发指南(VB2013版) 第四章 Excel编程
    VSTO开发指南(VB2013版) 第三章 Excel编程
    VSTO开发指南(VB2013版) 第二章 Office解决方案介绍
    VSTO开发指南(VB2013版) 第一章 Office对象模型
    打印预览
    打印
    工具函数
    开始使用
    模版对应信息
    解决PLSQL或者sqlplus连接oracle慢的方法
  • 原文地址:https://www.cnblogs.com/Code-Handling/p/13139241.html
Copyright © 2020-2023  润新知