关于ArrayList的contains方法
需求:只要名字相同,就判断是同一个用户
1、重写equals方法
public static class Student{ private String name; private int age; // @Override // public int hashCode(){ // final int prime = 31; // int result = 1; // result = prime * result + ((name == null) ? 0 : name.hashCode()); // return result; // } @Override public boolean equals(Object antObject){ if(this == antObject){ return true; } if(antObject instanceof Student){ Student anotherStu = (Student) antObject; if(this.name.equals(anotherStu.name) && this.age == anotherStu.age){ return true; } return false; } return false; } 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; } }
2、运行结果