Requirements: Remove duplicate elements from the ArrayList collection
Import Java.util.*;class arraylisttest{ Public Static void Main(string[] args) {ArrayList Al =NewArrayList (); Al.add ("1"); Al.add ("2"); Al.add ("1"); Al.add ("2"); Al.add ("1"); Al.add ("3"); Al.add ("4"); Al.add ("1"); SOP (AL); ArrayList Newal = Singleelement (AL); SOP (Newal); System. out. println ("Hello world!");//The next call in the loop in the iteration will be hasnext judged once} Public StaticArrayListsingleelement(ArrayList al) {ArrayList Newal =NewArrayList (); Iterator it = Al.iterator (); while(It.hasnext ()) {Object obj = It.next ();if(!newal.contains (obj)) {Newal.add (obj); } }returnNewal; } Public Static void SOP(Object obj) {System. out. println (obj); }}
[1, 2, 1, 2, 1, 3, 4, 1]
[1, 2, 3, 4]
Hello world!
Example:
//list set determines whether the element is the same, based on the Equals method of the elementImportJava.util.*;class person{PrivateString name;Private intAge Person (String name,intAge) { This. name = name; This. Age = Age; } PublicStringGetName() {returnName } Public int Getage() {returnAge } Public Boolean equals(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; }}
Class ArrayListTest2 { Public Static void SOP(Object obj) {System. out. println (obj); } Public Static void Main(string[] args) {ArrayList Al =NewArrayList ();//al.add (Object obj); Object obj = new Person ("Zhangsan", +);Al.add (NewPerson ("Zhangshan", -)); Al.add (NewPerson ("Lisi", A)); Al.add (NewPerson ("Wangwu", at)); Al.add (NewPerson ("Wangwu", at)); Al.add (NewPerson ("Alex", -)); Al.add (NewPerson ("Alex", -)); Al = Singleelemenet (AL); Sop"Remove"+al.remove (NewPerson ("Alex", -))); Iterator it = Al.iterator (); while(It.hasnext ()) {Person P = (person) it.next (); SOP (P.getname () +"::"+p.getage ()); } }
public Static ArrayList singleelemenet (ArrayList al) {ArrayList Newal = new ArrayList (); Iterator it = Al.iterator (); while (It.hasnext ()) {Object obj = It.next (); if (!newal.contains (obj)) {Newal.add (obj); }} return Newal; }
Lisi......zhangshan
Wangwu......zhangshan
Wangwu......lisi
Wangwu......zhangshan
Wangwu......lisi
Wangwu......wangwu
Alex......zhangshan
Alex......lisi
Alex......wangwu
Alex......zhangshan
Alex......lisi
Alex......wangwu
Alex......alex
Alex......zhangshan
Alex......lisi
Alex......wangwu
Alex......alex
Removetrue
Zhangshan::20
Lisi::22
Wangwu::23
Code training Camp--arraylist