The Contains method of ArrayList

Source: Internet
Author: User

Today, using the Caontains method of the ArrayList class is a problem, I wrote a ArrayList that holds the user class but always returns False when List.contains (user) is called. To see the next ArrayList source code, the source code is as follows:

Public Boolean contains (object o) {return indexOf (O) >= 0,    } public int indexOf (object o) {if (o = = null) {for    (int i = 0; i < size; i++) if (elementdata[i]==null)    return i;} else {for    (int i = 0; i < size; i++) if (O.E Quals (Elementdata[i])    return i;} return-1;    }

The Contains method is found to invoke the O.equals (Elementdata[i]) method, where Elementdata[i] is an instance of the object class. That is to say, I actually compare user.equals (object) When I call List.contains, which of course returns false.


Correct method, rewrite the Equals method in the user class. The code is rewritten as follows:
    Publicboolean equals (Object obj) {    if (obj instanceofuser) {    User U = (user) obj;    Returnthis.username.equals (u.username)    &&this.password.equals (password);    }    Returnsuper.equals (obj);    }

 



From for notes (Wiz)



The Contains method of ArrayList

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.