详述ArrayList类contains方法

源码:

public boolean contains(Object o) {
        return indexOf(o) >= 0;
    }
public int indexOf(Object o) {
        return indexOfRange(o, 0, size);
    }

    int indexOfRange(Object o, int start, int end) {
        Object[] es = elementData;
        if (o == null) {
            for (int i = start; i < end; i++) {
                if (es[i] == null) {
                    return i;
                }
            }
        } else {
            for (int i = start; i < end; i++) {
                if (o.equals(es[i])) {
                    return i;
                }
            }
        }
        return -1;
    }


System.out.println(names.contains(data));
红色部分数据是String类型的对象,则contains方法实质上调用的是String对象中的equals
基本数据类型包装类,则contains方法实质上调用的是包装类中的equals
类类型,则contains方法实质上调用的是类类型中的equals

String类型:

        ArrayList<String> names = new ArrayList<String>();
        names.add("Jim");
        System.out.println(names.contains("Jim"));

分析:结果为true。代码运行时,由于indexOfRange()函数中转为了数组中的Jim是第0位元素,而参数Jim不为Null,所以进入else语句块,与第0位元素相同,equals()函数返回值为true,所以返回0;而indexof()也就返回0;所以contains()也就返回true。

包装类:

        ArrayList<Integer> scores = new ArrayList<Integer>();
        scores.add(100);
        System.out.println(scores.contains(100));

分析:结果为true。代码运行时,由于indexOfRange()函数中转为了数组中的100是第0位元素,而参数Jim不为Null,所以进入else语句块,第0位元素equals()函数返回值为true,所以返回0;而indexof()也就返回0;所以contains()也就返回true。

自定义类类型:

//自己创建的Student类
public class Student {
	private String id;
	Student(String id){
		this.id=id;
	}
	
}
        ArrayList<Student> student = new ArrayList<Student>();
        student.add(new Student("12121"));
        System.out.println(student.contains(new Student("12121")));

分析:结果为false。由于此时的输入值为两者的地址;而创建对象时地址会发生改变,所以在代码块运行时,由于与数组中的每一个元素都不同,equals()函数返回值一直为false,所以跳出循环,返回-1,而indexof()也就返回-1;所以contains()也就返回false。

重写equals:                                                                                                                                                                                             重写前:Object类中的equals

    public boolean equals(Object obj) {
        return (this == obj);
    }

        重写后:自定义类中的equals

@Override
    public boolean equals(Object o) {
        if(o instanceof Student) {
            Student stu =(Student) o;
            String tid=this.id;
            String oid=stu.id;
            return tid.equals(oid);
        }
        return false;
    }

分析:在自定义equals()方法后先通过instanceof来排除非本类对象,直接处理;再对所比较值完成判断。所以此时我们再次重新运行上面返回false的代码块

​
        ArrayList<Student> student = new ArrayList<Student>();
        student.add(new Student("12121"));
        System.out.println(student.contains(new Student("12121")));

​

会发现返回值已经变成了true。

发布了23 篇原创文章 · 获赞 0 · 访问量 335

猜你喜欢

转载自blog.csdn.net/LinDadaxia/article/details/105543804
今日推荐