List中的Contains方法内部其实是用对象的equals方法做比较,所以如果比较两个类就重写类的equals方法即可;而Set是调用equals和hashCode
public class Person { private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public boolean equals(Object obj) { Person person = (Person) obj; return this.name == person.getName(); } // @Override // public int hashCode() { // return 1; // } }
public class TestDemo { @Test public void func1(){ Person person=new Person(); person.setName("aaa"); person.setAge(20); Person person1=new Person(); person1.setName("aaa"); person1.setAge(22); List<Person> personList=new ArrayList<Person>(); personList.add(person); if(!personList.contains(person1)){ personList.add(person1); } Set<Person> personSet=new HashSet<Person>(); personSet.add(person); if(!personSet.contains(person1)){ personSet.add(person1); } System.out.println(""); } }
打开Person类的hasCode注释后,运行如下