1 import java.util.ArrayList; 2 import java.util.List; 3 4 public class ArrayList_Test { 5 public static void main(String[] args) { 6 List<Student> stus = new ArrayList<>(); 7 8 stus.add(new Student("zhangsan")); 9 stus.add(new Student("lisi")); 10 stus.add(new Student("zhangsan")); 11 stus.add(new Student("zhangsan")); 12 stus.add(new Student("wangwu")); 13 // 第一种 14 // for (int i = 0; i < stus.size() - 1; i++) { 15 // for (int j = i + 1; j < stus.size()-1; j++) { 16 // if (stus.get(i).getName().equals(stus.get(j).getName())) { 17 // stus.remove(stus.get(i)); 18 // } 19 // } 20 // } 21 // System.out.println(stus); 22 // 第二种 23 // 定义一个新集合 24 List<Student> stus2 = new ArrayList<>(); 25 for (int i = 0; i < stus.size(); i++) { 26 if (!stus2.contains(stus.get(i))) {// 内部调用了equals方法,所以比的是栈中的引用地址,所以要重写equals方法 27 stus2.add(stus.get(i)); 28 } 29 } 30 System.out.println(stus2); 31 32 } 33 } 34 35 class Student { 36 String name; 37 38 public Student(String name) { 39 this.name = name; 40 } 41 42 public String getName() { 43 return name; 44 } 45 46 public void setName(String name) { 47 this.name = name; 48 } 49 50 @Override 51 public String toString() { 52 return "Student [name=" + name + "]"; 53 } 54 55 @Override 56 public int hashCode() { 57 final int prime = 31; 58 int result = 1; 59 result = prime * result + ((name == null) ? 0 : name.hashCode()); 60 return result; 61 } 62 63 @Override 64 public boolean equals(Object obj) { 65 if (this == obj) 66 return true; 67 if (obj == null) 68 return false; 69 if (getClass() != obj.getClass()) 70 return false; 71 Student other = (Student) obj; 72 if (name == null) { 73 if (other.name != null) 74 return false; 75 } else if (!name.equals(other.name)) 76 return false; 77 return true; 78 } 79 80 }