ImportJava.util.*;/*Saves the custom object as an element into the ArrayList collection and removes the repeating element. For example: the Depositary object. Same name as the same age, as the same person. is a repeating element. Idea: 1, describe the person, encapsulate the data into the human object. 2, define the container and deposit the person. 3, remove. The list collection determines whether the element is the same, based on the Equals method of the element. */classperson{PrivateString name; Private intAge ; Person (String name,intAge ) { This. Name =name; This. Age =Age ; } Public Booleanequals (Object obj) {if(! (objinstanceofPerson )) return false; Person P=(person) obj; //System.out.println (this.name+ "..." +p.name); return This. Name.equals (P.name) && This. Age = =P.age; } /**/public String GetName () {return name; } public int Getage () {return age; }}class ArrayListTest2 {public static void sop (Object obj) {System.out.println (obj); } public static void Main (string[] args) {ArrayList Al = new ArrayList (); Al.add (New Demo ()); Al.add (New person ("lisi01"),//al.add (Object obj),//object obj = new Person ("lisi01", 30); Al.add (New person ("lisi02", 32)); Al.add (New person ("lisi02", 32)); Al.add (New person ("lisi04", 35)); Al.add (New person ("lisi03", 33)); Al.add (New person ("lisi04", 35)); Al = Singleelement (AL); SOP ("Remove:" +al.remove (New Person ("lisi03")),//remove method is also dependent on the element's Equals method. Iterator it = Al.iterator (); while (It.hasnext ()) {person P = (person) it.next (); SOP (P.getname () + "::" +p.getage ()); }} public static ArrayList singleelement (ArrayList al) { Defines a temporary container. ArrayList Newal = new ArrayList (); Iterator it = Al.iterator (); while (It.hasnext ()) {Object obj = It.next (); if (!newal.contains (obj)) newal.add (obj); } return Newal; }}
The Java collection collection-list-arraylist the custom object as an element into the ArrayList collection and removes the repeating element.