Home > Java > javaTutorial > body text

equals method of Object class

高洛峰
Release: 2016-12-16 10:32:48
Original
1406 people have browsed it

The default implementation of the equals method in the Object class is whether the current object reference and the reference of the object you want to compare are the same object. The return value of the equals method is boolean. j2sdk provides some classes, such as: String Data, etc. The equals method is rewritten. Example program:

Java code

public class TestEquals {   
    public static void main(String[] args) {   
        Cat c1 = new Cat(1, 2, 3);   
        Cat c2 = new Cat(1, 2, 6);   
        System.out.println(c1 == c2); //false   
        System.out.println(c1.equals(c2)); //false   
        String s1 = new String("hello");    
        String s2 = new String("hello");   
        String m1 = "hello";   
        String m2 = "hello";   
        System.out.println(s1 == s2); //false   
        System.out.println(m1 == m2); //true   
        System.out.println(s1.equals(s2));  //true   
    }   
}   
//实体类   
class Cat {   
    int color;   
    int height, weight;   
       
    public Cat(int color, int height, int weight) {   
        this.color = color;   
        this.height = height;   
        this.weight = weight;   
    }   
    //重写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;   
    }   
}
Copy after login



For more articles related to the equals method of the Object class, please follow PHP Chinese website!


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template