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