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
}


}
上一篇:【CSS】我总结的一些基本概念


下一篇:Collection集合