List contains()比较对象,需要重写对象的equals()和hashCode()方法。
package com.kanzhun.phoenix.admin.mytest;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
/**
* ContainsTest
*
* @author jibingbing
* @date 2018/10/30
**/
public class ContainsTest {
public static void main(String[] args) {
Student student1 = new Student(1, "ji", 100);
Student student2 = new Student(2, "ji", 100);
Student student3 = new Student(1, "ji1", 100);
List<Student> students = new ArrayList<>();
students.add(student1);
// students.add(student2);
students.add(student3);
System.out.println(students.contains(student2));
}
static class Student {
int id;
String name;
int score;
public Student(int id, String name, int score) {
this.id = id;
this.name = name;
this.score = score;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o;
return score == student.score &&
Objects.equals(name, student.name);
}
@Override
public int hashCode() {
return Objects.hash(name, score);
}
}
}