import java.util.ArrayList;
import java.util.Collection;
public class ContainsTest {
public static void main(String[] args) {
//建立集合
Collection C = new ArrayList();
//添加元素
C.add(1);
//判断是否包含
System.out.println(C.contains(1));//true
Integer m = new Integer(50);
C.add(m);
Integer n = new Integer(50);
//
System.out.println(C.contains(n));//true 说明底层已经重写了equals方法
Manager m1 = new Manager(100, "jack");
C.add(m1);
Manager m2 = new Manager(100, "jack");
//如果两个引用的编号和姓名一致,那说明包含,这样把底层的equals方法进行重写
//而contains在底层的时间使用equals方法判断是否重复
System.out.println(C.contains(m2));
//**********************************************contains(Object o)在ArrayList中的实现方法
// public boolean contains(Object o) {
// return indexOf(o) >= 0;
// }
//
// /**
// * Returns the index of the first occurrence of the specified element
// * in this list, or -1 if this list does not contain the element.
// * More formally, returns the lowest index <tt>i</tt> such that
// * <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>,
// * or -1 if there is no such index.
// */
// public int indexOf(Object o) {
// if (o == null) {
// for (int i = 0; i < size; i++)
// if (elementData[i]==null)
// return i;
// } else {
// for (int i = 0; i < size; i++)
// if (o.equals(elementData[i]))
// return i;
// }
// return -1;
// }
}
}
class Manager{
int number;
String name;
public Manager(int number,String name) {
this.number=number;
this.name=name;
}
public boolean equals(Object o){
if(this==o)
return true;
if (o instanceof Manager){
Manager s =(Manager)o;
if(s.number==this.number && s.name.equals(this.name)){
return true;
}
}
return false;
}
}
155_集合_Collection集合的常用方法详解_03_contains
最新推荐文章于 2022-09-06 10:56:29 发布