详述ArrayList中的contains方法

contains方法用于检测List中是否有该元素。

先来看看contains的源码

public boolean contains(Object o) {
        return indexOf(o) >= 0;
    }

调用了indexOf方法

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

使用String类的ArrayList做示范

ArrayList<String> list = new ArrayList();
list.add("hello");
String name = "hello";
System.out.println(list.contains(name)); //返回true

在indexOf中,调用String的equals方法,比较出两个字符串值相同,即hello存在于list中。

使用包装类

ArrayList<Integer> list = new ArrayList();
list.add(123);
System.out.println(list.contains(new Integer(123))); //结果也是true

Integer中的equals方法,先判断是否为Integer类,再进行值比较

public boolean equals(Object obj) {
    if (obj instanceof Integer) {
        return value == ((Integer)obj).intValue();
    }
    return false;
}

自定义类型

自定义Student类,调用ArrayList中的contains方法

package Test;

import java.util.ArrayList;

class Student {

	public String ID;
	
	Student(String ID) {
		this.ID = ID;
	}

}

public class Test {

	public static void main(String[] args) {

		ArrayList<Student> stu=new ArrayList<>();
		Student student =new Student("111");
		stu.add(student);
		System.out.println(stu.contains(new Student("111")));
	}
}

结果为false,因为equals比较的是对象的地址,显然不相同。

重写equals方法

@Override
public boolean equals(Object obj) {
	// TODO Auto-generated method stub
		Student s=(Student)obj;
		String TID=this.ID;
		String elementID=s.ID;
		return TID.equals(elementID);
	return false;
}

在Student类中添加了重写的equals方法,结果为true。

因为使用下转型,让equals比较Student中的ID,自然就可以正确的比较了

但如果传进来比较的对象是其他类型呢?

将String类与自定义类型进行contains比较

public static void main(String[] args) {
		ArrayList<Student> stu=new ArrayList<>();
		Student student =new Student("111");
		stu.add(student);
		System.out.println(stu.contains("111"));
	}

结果会抛出异常,所以我们需要添加一个检测,看传进来的对象是否为student类

@Override
public boolean equals(Object obj) {
	// TODO Auto-generated method stub
	if(obj instanceof Student) {
		Student s=(Student)obj;
		String TID=this.ID;
		String elementID=s.ID;
		return TID.equals(elementID);
		}
		return false;
	}

输出为true

注:变量名ID应该小写,太多了就先不改了,student应该创建简单Java类。


发表评论