Collection的retainAll和equals方法
阿新 • • 發佈:2021-07-28
package com.cheng.collection;
import java.util.ArrayList;
import java.util.Collection;
//coll.retainAll(coll1) 取coll和coll1集合的交集 並返回給coll(當前集合)
//equals 判斷兩集合內容是否相等
public class RetainAndEquals {
public static void main(String[] args) {
Collection coll = new ArrayList();
coll.add(123);
coll.add(456);
coll.add(123);
coll.add(new String("牛不牛"));
coll.add(false);
coll.add(new Person("Ali",24));
Collection coll1 = new ArrayList();
coll1.add(123);
coll1.add(new String("牛不牛"));
coll1.add(new Person("Ali",24));
coll.retainAll(coll1);//取交集
System.out.println(coll);//[123, 123, 牛不牛, Person{name='Ali', age=24}]
Collection coll2 = new ArrayList();
coll2.add(123);
coll2.add(456);
coll2.add(new String("牛不牛"));
coll2.add(false);
coll2.add(new Person("Ali",24));
System.out.println(coll.equals(coll2));//false
// 注意 此處是ArrlyList有序放的元素 若是元素一樣但是順序不一致也是false
}
}
Person類:
package com.cheng.collection;
import java.util.Objects;
public class Person {
private String name;
private int age;
public Person() {
}
public Person(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;
}