zoukankan      html  css  js  c++  java
  • 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方法。

    public class TestEquals {
    	public static void main(String[] args) {
    		Cat c1 = new  Cat("蓝色",2,3);
    		Cat c2 = new  Cat("蓝色",2,3);
    		System.out.println(c1 == c2);//false
    		System.out.println(c1.equals(c2));//true
    		
    		//调用String类  且String中已经有对于equals方法的重写了
    		String s1 = new String("hello");
    		String s2 = new String("hello");
    		System.out.println(s1 == s2);//false
    		System.out.println(s1.equals(s2));//true
    	}
    	
    }
    
    class Cat {
    	String color;
    	double height,weight;
    	
    	public Cat(String color,double height,double weight) {
    		this.color  = color;
    		this.height = height;
    		this.weight = weight;
    	}
    	//在Cat中重写equals方法
    	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;
    	}
    }
    
  • 相关阅读:
    软件测试作业4
    Android基础知识每日记(持续更新)
    二叉树操作总结
    No.223 Rectangle Area
    No.66 Plus One
    No.80 Remove Duplicates from Sorted Array ||
    No.27 Remove Element
    No.26 Remove Duplicates from Sorted Array
    No.9 Palindrome Number
    No.219 Contains Duplicate ||
  • 原文地址:https://www.cnblogs.com/lsswudi/p/11264411.html
Copyright © 2011-2022 走看看