问题
在对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方法。
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论