这是哪里错了呢
package com.imooc.set;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
public class CatTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
Cat huahua = new Cat("花花", 10, "英国短毛猫");
Cat fnafan = new Cat("凡凡", 2, "中华田园猫");
Set<Cat> set = new HashSet<Cat>();
set.add(huahua);
set.add(fnafan);
Iterator<Cat> it = set.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
Cat huahua1 = new Cat("花花二代", 10, "英国短毛猫");
set.add(huahua1);
it = set.iterator();
System.out.println("添加后的HashSet");
while (it.hasNext()) {
System.out.println(it.next());
}
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("花花没找到");
}
for (Cat cat : set) {
System.out.println(cat);
if ("花花".equals(cat.getName())) {
set.remove(cat);
}
}
System.out.println("输入删除后的元素");
System.out.println("==============================");
for (Cat cat : set) {
System.out.println(cat);
}
}
}package com.imooc.set;
public class Cat {
private String name;
private int month;
private String species;
public Cat(String name, int month, String species) {
super();
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;
}
public String toString() {
return "姓名:" + name + " 年龄:" + month + " 品种:" + species;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + month;
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((species == null) ? 0 : species.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Cat other = (Cat) obj;
if (month != other.month)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (species == null) {
if (other.species != null)
return false;
} else if (!species.equals(other.species))
return false;
return true;
}
}for循环那里删除就抛出异常了,这是咋回事呀。。。。。
0
收起
正在回答 回答被采纳积分+1
Java零基础入门18
- 参与学习 人
- 提交作业 7317 份
- 解答问题 14452 个
想要入门学编程?多年一直活跃在编程语言排行版前列的Java是一个很好的选择。本路径将从Java基础语法、面向对象、常用工具类三部分,为你开启软件开发的大门!
了解课程

恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星