1 import java.util.ArrayList; 2 import java.util.Iterator; 3 4 import cn.itcast.p1.bean.Person; 5 6 public class ArrayListTest2 { 7 8 public static void main(String[] args) { 9 10 ArrayList al = new ArrayList(); 11 12 al.add(new Person("lisi1",21)); 13 al.add(new Person("lisi2",22)); //與28行的Person,內容相同,地址不同 14 al.add(new Person("lisi3",23)); 15 al.add(new Person("lisi4",24)); 16 al.add(new Person("lisi2",22)); 17 al.add(new Person("lisi3",23)); 18 19 System.out.println(al); 20 21 al = getSingleElement(al); //去除重復方法 22 23 System.out.println(al); 24 25 System.out.println(al.remove(new Person("lisi2",22)));//remove內部是用equals來判斷刪除內容 26 System.out.println(al); 27 28 } 29 30 31 private static ArrayList getSingleElement(ArrayList al) { 32 ArrayList temp = new ArrayList(); 33 34 Iterator it = al.iterator(); 35 36 while (it.hasNext()) 37 { 38 Object obj = it.next(); 39 40 if (!temp.contains(obj)) 41 { 42 temp.add(obj); 43 } 44 } 45 46 return temp; 47 } 48 49 }