java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Java中List类的contains和indexOf方法区别

Java中List类的contains和indexOf方法的使用及区别

作者:Louis210

这篇文章主要介绍了Java中List类的contains和indexOf方法的使用及区别,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教

问题

在对List类的使用中,有一次使用到了contains和indexOf方法,而出现预期以外的错误,考虑到List中的元素都为引用类型,因此想知道List的contains和indexOf方法的结果是否与引用对象相关。

代码实例

如下:

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;
	}
	
}

运行结果

如下:

由此可见,如果List的泛型重写了equals方法,则contains和indexOf方法都可以正常工作,而不需要要求参数为List中的同一个引用对象,只需要值相同即可。

而将equals去掉之后,其他代码不变,发现结果如下:

发现contains和indexOf方法都判定newa这个对象不在peoples这个List中。

如果再将此行改为:

//使用contains
System.out.println(peoples.contains(a));
//使用indexOf
System.out.println(peoples.indexOf(a));

运行结果如下:

结果再一次正确。

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文