当前位置: 代码网 > it编程>编程语言>Java > Java中List类的contains和indexOf方法的使用及区别

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

2026年03月24日 Java 我要评论
问题在对list类的使用中,有一次使用到了contains和indexof方法,而出现预期以外的错误,考虑到list中的元素都为引用类型,因此想知道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));

运行结果如下:

结果再一次正确。

总结

  • contains和indexof方法是一致的。
  • 如果希望值相同就可以在list中找到,则需要重写list<l>的l中的equals方法。
  • 如果希望引用相同,则不可以重写l中的equals方法。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2026  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com