day10

學習內容:

  1. List長度可變,可存儲重複值,可以存儲null;

    ArrayList,使用數組實現,增刪性能差,查詢快;LinkedList,使用鏈表實現,增刪快,查詢慢。

-------------------------------------------------------------

作業:重寫equals

public class CollectionDemo {
	public static void main(String[] args) {
		Student s1 = new Student("tom", 12, 1);
		Student s2 = new Student("tom1", 12, 1);
		Student s3 = new Student("tom", 12, 1);
		System.out.println(s1 == s2);
		System.out.println(s1.equals(s3));
		System.out.println();
		List<Student> ss = new ArrayList<>();
		for (int i = 0; i < 100; i++) {
			ss.add(new Student("tom" + i, i, i % 2 == 0 ? 0 : 1));
		}
        System.out.println(ss.contains(new Student("tom10",10,0)));
        System.out.println(ss.remove(new Student("tom10",10,0)));
        System.out.println(ss.contains(new Student("tom10",10,0)));
	}
}

class Student {
	private String name;
	private int age;
	private int sex;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public int getSex() {
		return sex;
	}

	public void setSex(int sex) {
		this.sex = sex;
	}

	public Student(String name, int age, int sex) {
		super();
		this.name = name;
		this.age = age;
		this.sex = sex;
	}

	@Override
	public boolean equals(Object obj) {
		if (obj == null) {
			return false;
		}
		if (this == obj) {
			return true;
		}
		if (obj.getClass() == Student.class) {
			Student student = (Student) obj;
			if (this.getName() != null) {
				if (this.getName().equals(student.getName())) {
					if (this.getAge() == student.getAge()) {
						if (this.getSex() == student.getSex()) {
							return true;
						}
					}
				}
			} else {
				if (student.getName() == null) {
					if (this.getAge() == student.getAge() && this.getSex() == student.getSex()) {
						return true;
					}
				}
			}
		}
		return false;
	}
}

這樣可以判斷,list在調用contains(obj),remove(obj)等方法時,都會調用equal()來判斷集合中是否存在這個對象

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章