需求:去除集合中重复元素
分析:
1、临时容器存储
2、循环遍历集合(迭代)
3、判断元素是否已存在临时容器中(contains)
一、定义存储元素的类型(自定义类型)
1 public class Person { 2 3 private String name; 4 private int age; 5 6 public Person() { 7 super(); 8 } 9 10 public Person(String name, int age) { 11 super(); 12 this.name = name; 13 this.age = age; 14 } 15 16 public String getName() { 17 return name; 18 } 19 20 public void setName(String name) { 21 this.name = name; 22 } 23 24 public int getAge() { 25 return age; 26 } 27 28 public void setAge(int age) { 29 this.age = age; 30 } 31 32 @Override 33 public int hashCode() { 34 System.out.println(this + ":-------hashCode"); 35 return this.name.hashCode() + this.age; 36 } 37 38 @Override 39 public boolean equals(Object obj) { 40 System.out.println(this + ":-------equals-------" + obj); 41 if (!(obj instanceof Person)) 42 throw new ClassCastException("类型不对"); 43 Person person = (Person) obj; 44 return this.name.equals(person.name) && person.age == this.age; 45 } 46 47 @Override 48 public String toString() { 49 50 return this.name + ":" + this.age; 51 } 52 }
二、业务逻辑代码
1 import java.util.ArrayList; 2 import java.util.Iterator; 3 4 import cn.marw.common.bean.Person; 5 6 public class ArrayListTest { 7 8 public static void main(String[] args) { 9 ArrayList arr = new ArrayList(); 10 11 arr.add(new Person("zhang1", 21)); 12 arr.add(new Person("zhang2", 22)); 13 arr.add(new Person("zhang3", 23)); 14 arr.add(new Person("zhang4", 24)); 15 arr.add(new Person("zhang2", 22)); 16 17 System.out.println("去重前:-----" + arr); 18 19 arr = getSignalElement(arr); 20 21 System.out.println("去重后:-----" + arr); 22 } 23 24 private static ArrayList getSignalElement(ArrayList arr) { 25 ArrayList temp = new ArrayList(); 26 Iterator it = arr.iterator(); 27 while (it.hasNext()) { 28 Person p = (Person) it.next(); 29 30 if (!temp.contains(p)) { 31 temp.add(p); 32 } 33 } 34 return temp; 35 } 36 }
结果:
总结:
ArrayList判断集合元素是否相同,就是看元素的equals
ArrayList的方法contains和remove都要看元素的equals