Java中List類的contains和indexOf方法的使用及區(qū)別
問題
在對(duì)List類的使用中,有一次使用到了contains和indexOf方法,而出現(xiàn)預(yù)期以外的錯(cuò)誤,考慮到List中的元素都為引用類型,因此想知道List的contains和indexOf方法的結(jié)果是否與引用對(duì)象相關(guān)。
代碼實(shí)例
如下:
import java.util.ArrayList;
import java.util.List;
public class Temp
{
public static void main(String[] args) throws Exception
{
List<String> list = new ArrayList<String>();
for (int i = 0; i < 10; i++) {
list.add(String.valueOf(i));
}
//使用contains
System.out.println(list.contains("5"));
//使用indexOf
System.out.println(list.indexOf("5"));
System.out.println(list.indexOf(new String("5")));
List<People> peoples = new ArrayList<People>();
People a = new People("a");
People b = new People("b");
People newa = new People("a");
peoples.add(a);
peoples.add(b);
//使用contains
System.out.println(peoples.contains(newa));
//使用indexOf
System.out.println(peoples.indexOf(newa));
}
}
class People{
private String name;
/**
* @param name
*/
public People(String name) {
this.name = name;
}
@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 obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
People other = (People) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
/**
* @return the name
*/
public String getName() {
return name;
}
}運(yùn)行結(jié)果
如下:

由此可見,如果List的泛型重寫了equals方法,則contains和indexOf方法都可以正常工作,而不需要要求參數(shù)為L(zhǎng)ist中的同一個(gè)引用對(duì)象,只需要值相同即可。
而將equals去掉之后,其他代碼不變,發(fā)現(xiàn)結(jié)果如下:

發(fā)現(xiàn)contains和indexOf方法都判定newa這個(gè)對(duì)象不在peoples這個(gè)List中。
如果再將此行改為:
//使用contains System.out.println(peoples.contains(a)); //使用indexOf System.out.println(peoples.indexOf(a));
運(yùn)行結(jié)果如下:

結(jié)果再一次正確。
總結(jié)
- contains和indexOf方法是一致的。
- 如果希望值相同就可以在List中找到,則需要重寫List<L>的L中的equals方法。
- 如果希望引用相同,則不可以重寫L中的equals方法。
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Vue3實(shí)現(xiàn)多頁(yè)面跳轉(zhuǎn)效果的幾種方式
Vue.js是一個(gè)用于構(gòu)建用戶界面的漸進(jìn)式 JavaScript 框架,它提供了多種方法來實(shí)現(xiàn)頁(yè)面之間的導(dǎo)航,在 Vue 3 中,頁(yè)面跳轉(zhuǎn)主要通過 Vue Router 來管理,同時(shí)也支持其他方式如編程式導(dǎo)航和使用錨點(diǎn)鏈接,本文將詳細(xì)介紹 Vue 3 中的各種頁(yè)面跳轉(zhuǎn)方式,需要的朋友可以參考下2025-03-03
springboot aop切到service層,不生效問題
這篇文章主要介紹了springboot aop切到service層,不生效問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-05-05
Java實(shí)現(xiàn)獲取指定個(gè)數(shù)的不同隨機(jī)數(shù)
今天小編就為大家分享一篇關(guān)于Java實(shí)現(xiàn)獲取指定個(gè)數(shù)的不同隨機(jī)數(shù),小編覺得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來看看吧2019-01-01
Java文件讀取寫入后 md5值不變的實(shí)現(xiàn)方法
下面小編就為大家分享一篇Java文件讀取寫入后 md5值不變的實(shí)現(xiàn)方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助2017-11-11
SpringBoot上傳文件并配置本地資源映射來訪問文件的實(shí)例代碼
這篇文章主要介紹了SpringBoot上傳文件并配置本地資源映射來訪問文件的實(shí)例代碼,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-04-04

