62,634
社区成员




import java.util.*;
public class Demo1 {
public static void main(String[] args) {
Collection c=new ArrayList();
Person p=new Person(12,"狗娃")
c.add(p);
System.out.println("集合c中的id为"+c.contains(p));
}
}
class Person{
int id;
String name;
public Person(int id,String name) {
this.id=id;
this.name=name;
}
@Override
public boolean equals(Object obj) {
Person p=(Person)obj;
return this.id==id;//判断id是否相等?
}
@Override
public int hashCode() {
return this.hashCode();
}
}
// 判断是否包含o对象
public boolean contains(Object o) {
return indexOf(o) >= 0;
}
public int indexOf(Object o) {
// 如果o为null,则循环当前集合判断有没有null
if (o == null) {
for (int i = 0; i < size; i++)
if (elementData[i]==null)
return i;
} else {
// 如果o不是null,则循环集合判断有没有于o equals的对象
for (int i = 0; i < size; i++)
if (o.equals(elementData[i]))
return i;
}
return -1;
}