zoukankan      html  css  js  c++  java
  • Java-20,object类之equals方法

    equals方法

    • Object类中定义有:
      • public boolean equals(Object obj)方法
        • 提供定义对象是否“相等”的逻辑
      • Object的equals方法定义为:x.equals(y) 当x 和 y 是同一对象的应用时返回true 否则返回 false
      • J2SDK提供的一些类,如String,Date等,重写了Object的equals方法,调用这些类的equals方法,x.equals(y),当x和y所引用的对象是同一类对象且属性内容相等时(并不一定是相同对象),返回true否则返回false
      • 可以根据需要在用户自定义类型中重写equals方法。

    示例:

    package com.nyist;
    
    public class TestEquals {
        public static void main(String[] args) {
            Cat c1 = new Cat(1,2,3);
            Cat c2 = new Cat(1,2,3);
            System.out.println(c1 == c2);
         System.out.println(c1.equals(c2));

         } }
    class Cat{ int color; int height,weight; public Cat(int color,int height,int weight) { this.color = color; this.height = height; this.weight = weight; } }

    结果:

    false
    false

    equals方法的默认实现和==是一样的,都是比较是否是同一引用。

    通过重写可以实现只比较两对象是否实质是一样的。

    示例:

    package com.nyist;
    
    public class TestEquals {
        public static void main(String[] args) {
            Cat c1 = new Cat(1,2,3);
            Cat c2 = new Cat(1,2,3);
            System.out.println(c1.equals(c2));
        }
    }
    
    class Cat{
        int color;
        int height,weight;
        
        public Cat(int color,int height,int weight) {
            this.color = color;
            this.height = height;
            this.weight = weight;
        }
        
        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.height ==this.height && c.weight == this.weight)
                        return true;
                }
            }
            return false;
        }
    }

    结果:

    true
  • 相关阅读:
    P1659 [国家集训队]拉拉队排练
    manacher小结
    P4555 [国家集训队]最长双回文串
    P3649 [APIO2014]回文串
    P3899 [湖南集训]谈笑风生
    插头dp练习
    luoguP3066 [USACO12DEC]逃跑的BarnRunning
    luoguP3769 [CH弱省胡策R2]TATT
    android 广播,manifest.xml注册,代码编写
    *.db-journal 是什么(android sqlite )数据库删除缓存
  • 原文地址:https://www.cnblogs.com/nyist0/p/12449526.html
Copyright © 2011-2022 走看看