JAVA中的Hashset
Cat类
package com.ZBC;
import java.util.Objects;
public class Cat {
private String name;
private int month;
private String species;
public Cat(String name, int month, String species) {
this.name = name;
this.month = month;
this.species = species;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getMonth() {
return month;
}
public void setMonth(int month) {
this.month = month;
}
public String getSpecies() {
return species;
}
public void setSpecies(String species) {
this.species = species;
}
@Override
public String toString() {
return "{" +
"姓名='" + name + '\'' +
", 月份=" + month +
", 年龄='" + species + '\'' +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o.getClass() == Cat.class) {
Cat cat = (Cat) o;
return cat.getName().equals(name) && cat.getName().equals(name) && (cat.getMonth() == month);
}
return false;
}
@Override
public int hashCode() {
return Objects.hash(getName(), getMonth(), getSpecies());
}
}
Main方法
package com.ZBC;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
public class Main {
public static void main(String[] args) {
Cat huahua = new Cat("花花", 12, "英国短毛猫");
Cat fanfan = new Cat("凡凡", 3, "中华田园猫");
Set<Cat> set = new HashSet<>();
set.add(huahua);
set.add(fanfan);
Iterator<Cat> it = set.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
Cat huahua01 = new Cat("花花", 12, "英国短毛猫");
set.add(huahua01);
System.out.println("******************");
System.out.println("添加重复数据后的宠物猫信息为:");
it = set.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
Cat huahua02 = new Cat("花花二代", 2, "英国短毛猫");
set.add(huahua02);
System.out.println("添加花花二代后的宠物猫信息:");
it = set.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
System.out.println("******************");
if (set.contains(huahua)) {
System.out.println("花花找到了!");
System.out.println(huahua);
} else {
System.out.println("花花没找到!");
}
System.out.println("*************");
System.out.println("通过名字查找花花的信息");
boolean flag = false;
Cat c = null;
it = set.iterator();
while (it.hasNext()) {
c = it.next();
if (c.getName().equals("花花")) {
flag = true;
break;
}
}
if (flag) {
System.out.println("花花找到了!");
System.out.println(c);
} else {
System.out.println("花花没找到!");
}
Set<Cat> set1=new HashSet();
it=set.iterator();
for(Cat cat:set){
if("花花二代".equals(cat.getName())){
set1.add(cat);
}
}
set.removeAll(set1);
System.out.println("删除花花二代后的数据");
for(Cat cat:set){
System.out.println(cat);
}
System.out.println("*********");
boolean flag1= set.removeAll(set);
if (flag1) {
System.out.println("猫都不见了~");
}else{
System.out.println("猫还在~");
}
}
}
输出结果:
|