/* Store custom objects in ArrayList in order to implement an object that stores duplicates in ArrayList, you need to override the Equals method. Both the Remove () method and The contains () method call the Equals () method. When using HashSet, you also override the two methods in the object class, namely, the Hashcode () and the Equals () methods. Because HashSet will call these two functions at the bottom. Compare Hashcode (object reference or address) first, and then compare objects with equals if they are the same. */import java.util.*;class person{private String name;private int age; Person (String Name,int age) {this.name=name;this.age=age;} Public String GetName () {return name;} public int getage () {return age;} public boolean equals (object obj)//In order to compare object contents, override the Equals method {if (! obj instanceof person) return false; Person p= (person) Obj;return this.name.equals (p.name) && this.age==p.age;}} Class ArrayListTest2 {public static void main (string[] args) {ArrayList al=new ArrayList (); Al.add (The New person ("jhon_1", 20 ), Al.add (New person ("jhon_2")), Al.add ("Jhon_3"), Al.add (New person ("Jhon_3")), Al.add (new Person ("Jhon_5"), Al.add ("Jhon_3"),//sop (AL), SOP (Al.remove ("Jhon_5", 20)); The lower level also uses the Equals method. Al=quchong (AL); Iterator It=al.iterator (); while (It.hasnext ()) {ObJect Obj=it.next (); Person p= (person) Obj;sop (P.getname () + "..." +p.getage ()); System.out.println ("Hello world!");} public static ArrayList Quchong (ArrayList al) {ArrayList al_des=new ArrayList (); Iterator it=al.iterator (); while ( It.hasnext ()) {Object obj=it.next (); if (!al_des.contains (obj))//contains calls equals at the bottom. But the original Equals method is to compare the object's address, not to compare the object content, so it needs to be rewritten. Al_des.add (obj);} return al_des;} public static void Sop (Object obj) {System.out.println (obj);}}
Java Collection Framework-arraylist store non-repeating custom objects