Set collection can add repeating elements

Source: Internet
Author: User

Set sets determine the uniqueness of elements to override the hashcode and equals methods so that duplicate elements are not added,

However, in the following cases, you can add duplicate elements, even if their hashcode and equals methods result in the same

 Public Static voidMain (string[] args) {Set<Person> set =NewHashset<person>(); Person P1=NewPerson ("P1", 123); Person P2=NewPerson ("P2", 123); Person P3=NewPerson ("P3", 123);        Set.add (p1);        Set.add (p2);                Set.add (p3); Iterator<Person> it=Set.iterator ();  while(It.hasnext ()) {person P=It.next (); System.out.println (P.getname ()+":"+p.getage ()); } p3.setage (20);        Set.remove (p3);        Set.add (p3); System.out.println ("---------------------"); It=Set.iterator ();  while(It.hasnext ()) {person P=It.next (); System.out.println (P.getname ()+ ":" +p.getage () + ":" +P.hashcode ()); }            }
classperson{PrivateString name; Private intAge ;  PublicPerson () {} PublicPerson (String name,intAge ) {         This. Name =name;  This. Age =Age ; }    /*** return *@return      */     PublicString GetName () {returnname; }    /*** Set *@param      */     Public voidsetName (String name) { This. Name =name; }    /*** return *@return      */     Public intGetage () {returnAge ; }    /*** Set *@param      */     Public voidSetage (intAge ) {         This. Age =Age ; } @Override Public inthashcode () {return  This. Age; } @Override Public Booleanequals (Object obj) {if(objinstanceofPerson ) {Person P=(person) obj; returnP.getname (). Equals ( This. GetName ()); }        return false; }    }

The Element property value (hashcode value) in the Modify set is removed when the element is removed because it will find the secondary object based on the modified Hashcode value, and the deletion failure is obviously not found.

You can add this object again, although their hashcode and equals are the same but they are stored in a different location

Set collection can add repeating elements

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.