廖雪峰Java5集合-2List-2编写equals方法
List
- List内部按照放入元素的先后顺序存放
- 每个元素都可以通过索引确定自己的位置
- boolean contains(Object o) 是否包含某个元素
- int indexOf(Object o) 查找某个元素的索引,不存在返回-1
1.String\Integer等已经覆写了equals方法
import java.util.*;
public class Main {
public static void main(String[] args){
List<String> list = new ArrayList<>();
list.add("hello");
list.add("world");
list.add(null);
list.add(3,"java");
list.add(4,"python");
System.out.println(list.toString()+"是否包含null:"+list.contains(null));
System.out.println(list.toString()+"是否包含hello:"+list.contains("hello"));
System.out.println(list.toString()+"是否包含ruby:"+list.contains("ruby"));
System.out.println(list.toString()+"hello的索引::"+list.indexOf("hello"));
System.out.println(list.toString()+"ruby的索引:"+list.indexOf("ruby"));
}
}
![](https://img2018.cnblogs.com/blog/1418970/201903/1418970-20190306214907642-519465255.png)
![](https://img2018.cnblogs.com/blog/1418970/201903/1418970-20190311202129637-2094147861.png)
Person.java
package com.testList;
public class Person {
private String name;
private int age;
public Person(String name,int age){
this.name = name;
this.age = age;
}
public String getName(){
return this.name;
}
public int getAge(){
return this.age;
}
@Override
public String toString(){
return "(Person:"+name+","+age+")";
}
}
Main.java
import java.util.*;
public class Main {
public static void main(String[] args){
List<Person> list = new ArrayList<>();
list.add(new Person("小明",12));
list.add(new Person("小红",15));
list.add(new Person("小军",13));
System.out.println(list);
System.out.println(list.contains(new Person("小军",13)));
}
}
![](https://img2018.cnblogs.com/blog/1418970/201903/1418970-20190306221613575-917066922.png)
在Person类中并没有覆写Objects.equals()方法,此时equals使用==来判断2个Object的引用,因此contains返回是false。为了修复这个逻辑,使contains返回true,此时要编写equals方法
重写equals方法
public boolean equals(Object o){
if (this == o){
return true;
}
if (o instanceof Person){
Person p = (Person) o;
return p.name.equals(this.name) && p.age == this.age;
}
return false;
}
System.out.println(list.contains(new Person("小红",15)));
![](https://img2018.cnblogs.com/blog/1418970/201903/1418970-20190311195954813-1051728095.png)
![](https://img2018.cnblogs.com/blog/1418970/201903/1418970-20190311195849615-1735989840.png)
}
return false;
}
<img src="https://img2018.cnblogs.com/blog/1418970/201903/1418970-20190311200855542-421064474.png" width="500" />
使用JDK Objects自带的equals方法精简代码
```#java
public boolean equals(Object o){
if (this == o){
return true;
}
if (o instanceof Person){
Person p = (Person) o;
return Objects.equals(p.name,this.name) && p.age == this.age;
}
return false;
}
![](https://img2018.cnblogs.com/blog/1418970/201903/1418970-20190311201124510-2087666355.png)
总结:
如果要在List中查找元素:
- List的实现类通过元素的equals方法比较两个元素
- 放入的元素必须正确覆写equals方法
* jdk提供的String、Integer等已经覆写了equals方法 - 编写equals方法可借助Objects.equals()判断
如果不在List中查找元素:
- 不必覆写equals方法