One practicepackage collection;import java.util.arraylist;import java.util.iterator;//Remove duplicate elements from ArrayList collection public Class Arraylisttest{public static void Sop (Object obj) {System.out.println (obj);} public static void Main (string[] args) {arraylist<string> ArrayList = new arraylist<string> (); Arraylist.add ("Java01"); Arraylist.add ("java02"); Arraylist.add ("java03"); Arraylist.add ("java04"); Arraylist.add ("Java01"); Arraylist.add ("Java02"); Arraylist.add ("java03"); SOP (arrayList); arrayList = Singleelement (arrayList); SOP ( arrayList);} public static arraylist<string> Singleelement (arraylist<string> al) {//define a temporary container ArrayList Newal = new ArrayList (); Iterator Iterator = Al.iterator (); while (Iterator.hasnext ()) {Object obj = Iterator.next (); if (! Newal.contains (obj)) {newal.add (obj);}} return Newal;}} Practice Twopackage Collection;import Java.util.arraylist;import java.util.iterator;//to save the custom object as an element into the ArrayList collection, and remove duplicate elements//such as: Depositary Objects. Same name as the same age, as the same person. /*1 for repeating elements. Describes a person, encapsulates the data into Object 2. Define the container and deposit the person 3. Remove LThe IST collection determines whether the element is the same, based on the Equals method of the element. */class person{private String name;private int age; Person (String Name,int age) {this.name = Name;this.age = age;} Override the Equals method public boolean equals (Object obj) {if (! ( obj instanceof person) {return false;} Person person = (person) Obj;return this.name.equals (person.name) && this.age = = person.age;} Public String GetName () {return name;} public int getage () {return age;}} public class Arraylisttest2{public static void Sop (Object obj) {System.out.println (obj);} public static void Main (string[] args) {ArrayList Al = new ArrayList (); Al.add (The New person ("XP01")); Al.add (The New person ("X ("P02"), Al.add ("Xp02"), Al.add (New person ("XP03", PNS)), Al.add (New person ("Xp04"), Al.add (new); Person ("Xp04", "N"); Al = Singleelement (AL); Iterator it = Al.iterator (); while (It.hasnext ()) {person P = (person) it.next () SOP (P.getname () + "::" +p.getage ());}} public static ArrayList Singleelement (arraylist<string> al) {//define a temporary container ArrayList Newal = new ArrayList (); IteRator iterator = Al.iterator (), while (Iterator.hasnext ()) {Object obj = Iterator.next (); if (!newal.contains (obj)) { Newal.add (obj);}} return Newal;}}
Java removes duplicate elements from the ArrayList collection