详述ArrayList类中contains方法

源码:
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<String> names = new ArrayList<String>();
		names.add("aa");
		System.out.println(names.contains("aa"));

分析:System.out.println(names.contains(“aa”));中的names.contains(“aa”) 是contains代码中的 o,然后转到indexOf源码执行:和已有的数据比较,判断是否有相同的数据,有,则return i,使得contains中 return indexOf(o) >= 0;值为吐ture,String类型输出ture。
否则return 0 ,使得contains中 return indexOf(o) >= 0;值为false,String类型输出false。

包装类:

ArrayList<Integer> ages = new ArrayList<Integer>();
	    ages.add(12);
	    System.out.println(ages.contains(new Integer(12)));

分析:
Integer中equals源码:

public boolean equals(Object obj) {
        if (obj instanceof Integer) {//判断是否是Integer类
            return value == ((Integer)obj).intValue();//判断是否为值相等,并返回ture或false,然后转到contains中的 return indexOf(o) >= 0; 来判断并返回值
        }
        return false;//如果不是Integer,则直接false
    }

对于包装类,则是比较值是否相同。

自定义类型:

需先定义一个类:

public class Student {

	private String id;
	public Student(String id) {
		this.id = id;
		
	}
}

自定义类型

ArrayList<Student> students = new ArrayList<Student>();
	    students.add(new Student("111"));
	    System.out.println(students.contains(new Student("222")));

分析:
未重写之前:

public class Student {

	private String id;
	public Student(String id) {
		this.id = id;
		
	}
}

Object中的epuals:

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

因为Student中无epuals,则自定义类型调用Object中的epuals。而Object中的epuals是用来比较地址的,而自定义类型中创建了俩个Student对象地址一定不同,则一定输出false。

重写之后:
分析:

public class Student {

	private String id;
	public Student(String id) {
		this.id = id;
		
	}
	@Override
	public boolean equals(Object obj) {
		Student s = (Student)obj;//下转型对象使得可以使用本类新定义的属性,s 为Student已添加的数据
		String argId = this.id;
		String elementId = s.id;
		return argId.equals(elementId);//一个一个比较System.out.println(students.contains(new Student("222"))); 中的new Student("222")和Student中的数据是否有相同的
	}
}

instanceof:
当自定义类型中的数据类型开放后:

ArrayList<Object> List = new ArrayList<Object>();//数据类型为Object
	    List.add(new String());//输入的数据类型为String
	    System.out.println(List.contains(new Student("111")));

此时:重写的equals代码中:Student s = (Student)obj; 则是一个将String类型的字符串下转型给Student。这是不可能的,会报错,所以,此时我们在equals中判断是否有相同数据前,要判断是否是同一种数据类型,是否可以下转型,即使用instanceof

@Override
	public boolean equals(Object obj) {
		if(obj instanceof Student) {
			Student s = (Student)obj;
			String argId = this.id;
			String elementId = s.id;
			return argId.equals(elementId);
		}
		return false;
	}
发布了28 篇原创文章 · 获赞 0 · 访问量 419

猜你喜欢

转载自blog.csdn.net/syhfly2333/article/details/105544062
今日推荐