Comparison of "Java 0 Basic Starter series" DAY15 objects

Source: Internet
Author: User

Recently has been something, blog also stopped pen for some time, very sorry.

This article is mainly about the comparison of objects, what is the comparison of objects, we know that two numeric types only need to use the "= =" symbol can be equal judgment, but if it is two goods object? How do I compare them? At this point, our Equals method comes in handy. The Equals method is another protected method of the Ancestor object class of the class, since it is the protected method (which can be accessed by all classes in the same package, can be accessed by subclasses of the class, the subclass is not in a package with the parent class), and the subclass can be accessed directly, However, if this method is not overridden, then only the original comparison method of object is used, return (this==obj), only compares the address of two objects is consistent.

For the string type, the Equals method has been designed, so we just need to use it, if it is our custom class, then we have to rewrite the method to overwrite, or use the goods class to lift a small chestnut:

 Public classGoods {PrivateString title; Private DoublePrice ;  PublicString GetTitle () {returntitle; }     Public voidSettitle (String title) { This. title =title; }     Public DoubleGetPrice () {returnPrice ; }     Public voidSetprice (DoublePrice ) {         This. Price =Price ; }    //Constructors     PublicGoods (String title,DoublePrice ) {         This. title =title;  This. Price =Price }
}

This is a simplified version of the goods class, there are two private member variables and their settings, accessors, and a constructor, let's rewrite the Equals method of the parent class to determine whether two goods are equal, logically, We just need the two titles and the price to agree that both goods are equal (of course can be adjusted according to the actual situation), let's design the Equals method:

/** * @authorFrank * @create 2017/11/20 * @description tested class, Test Equals method*/ Public classGoods {PrivateString title; Private DoublePrice ;  PublicString GetTitle () {returntitle; }     Public voidSettitle (String title) { This. title =title; }     Public DoubleGetPrice () {returnPrice ; }     Public voidSetprice (DoublePrice ) {         This. Price =Price ; }    //Constructors     PublicGoods (String title,DoublePrice ) {         This. title =title;  This. Price =Price ; }    //overriding the Equals method@Override Public Booleanequals (Object obj) {Goods tmp=(Goods) obj; if(Price = = Tmp.getprice () &&title.equals (Tmp.gettitle ())) {            return true; }Else {            return false; }    }}

Here we override the Equals method of the parent class, cast the obj type to the goods class in the Equals method, and then compare the price and the caption for equality, as long as they are equal, return true, otherwise return false, which is also in line with our requirements, test it below:

/** * @authorFrank * @create 2017/11/20 * @description Test class for testing the Equals method*/ Public classTest { Public Static voidMain (string[] args) {Goods a=NewGoods ("Java", 100); Goods b=NewGoods ("C + +", 100); Goods C=NewGoods ("Java", 100);        System.out.println (A.equals (b));    System.out.println (A.equals (c)); }}

The output is: false ture

So we can simply implement the Equals method, but this equals method is not perfect, first of all, because we passed in the object, so we do not know whether its original type is goods type, if not goods type, of course, can not be compared, So we have to make the type judgments first:

@Override Public Booleanequals (Object obj) {//Type judgment        if(Obj.getclass ()! = This. GetClass ()) {            return false; }Else{Goods tmp=(Goods) obj; if(Price = = Tmp.getprice () &&title.equals (Tmp.gettitle ())) {                return true; }Else {                return false; }        }    }

is still imperfect, if the object being compared is itself or the two point to the same object, return true directly:

@Override Public Booleanequals (Object obj) {//Check for self-comparison first        if( This= = Obj | | obj = =NULL){            return true; }        //Type judgment        if(Obj.getclass ()! = This. GetClass ()) {            return false; }Else{Goods tmp=(Goods) obj; if(Price = = Tmp.getprice () &&title.equals (Tmp.gettitle ())) {                return true; }Else {                return false; }        }    }

It's a lot better now, so what's the difference between calling the Equals method and using the "= =" comparison symbol, and looking at a chestnut:

 Public classTest { Public Static voidMain (string[] args) {Goods a=NewGoods ("Java", 100); Goods b=NewGoods ("C + +", 100); Goods C=NewGoods ("Java", 100); Goods D=A;        System.out.println (A.equals (b));        System.out.println (A.equals (c));        System.out.println (A.equals (d)); System.out.println (A==b); System.out.println (A==c); System.out.println (A==d); }}

The output is as follows:

false true true false false true

For the first three output should be no problem, the main look at the last three, where the equality of the comparison, the judge is only two variables stored in the consistency of the content, because a, B, C, d are reference types, so the comparison is only if they point to the same object, here only a and D point to the same object, C Although the title and price are the same as a, but with a is two completely different objects, so there is no return is false.

In addition, some people may ask, when doing type judgment, why do not use instanceof or Isinstance method, here briefly explain the reason. instance determines whether a object belongs to the same class as the B object, or has the same parent class, or implements the same interface. The Isinstance method determines whether two types can be strongly turned.

Since this little chestnut does not have the relevant context, it is safe to use the GetClass method to judge, of course, in the future can be modified according to the specific situation.

At this point, the Equals method is complete, very simple. After that will continue to update, welcome to continue to pay attention!

Java 0 Basic Starter Series DAY15 objects comparison

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.