1. 程式人生 > 其它 >Collection裡equals的重寫

Collection裡equals的重寫

package com.bo.collection;
//Collection
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

public class Demo02 {
public static void main(String[] args) {
Collection collection = new ArrayList();

Student s1 = new Student("趙",20);
Student s2 = new Student("錢",21);
Student s3 = new Student("孫",22);
//新增資料
collection.add(s1);
collection.add(s2);
collection.add(s3);
collection.add(s3);
System.out.println("元素個數:"+collection.size());
System.out.println(collection.toString());
//刪除
collection.remove(s1);
//從集合中清楚collection.clear(); 物件不會消失消失的是集合裡物件的地址
System.out.println("刪除之後:"+collection.size());
//遍歷
//增強for
for (Object objcet:collection ){
Student s =(Student) objcet;
System.out.println(s);
}
System.out.println("------------------------");
//迭代器
Iterator it = collection.iterator();
while(it.hasNext()){
Student s= (Student) it.next();
System.out.println(s);
}
//判斷
System.out.println(collection.contains(s2));
System.out.println(collection.isEmpty());

}
}


package com.bo.collection;

import java.util.Objects;

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

public Student() {
}

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

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

@Override
public String toString() {
return "Student{" +
"name=" + name +
", age=" + age +
'}';
}

@Override
public boolean equals(Object o) {
if (this == o) return true;//判斷是不是同一個物件
if (o == null ) return false;//判斷是否為空
//判斷是否是Student型別
if (o instanceof Student){
Student s =(Student) o;
if (this.name.equals(s.getName())&&this.age== s.getAge());
return true;}
return false;//不滿足條件返回false
}


}