首先定义一个猫类
package cn.hpu.set;
public class Cat {
private String name;
private int month;
private String species;
//构造方法
public Cat() {
}
public Cat(String name,int month,String species) {
this.setName(name);
this.setMonth(month);
this.setSpecies(species);
}
//对应属性的get和set方法
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
//重写toString方法
public String toString() {
return "Cat [姓名=" + name + ", 年龄=" + month + ", 品种=" + species + "]";
}
}
实例化猫类对象,将猫类对象添加到HashSet中
package cn.hpu.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("花花",12,"英国短毛猫");
Cat fanfan=new Cat("凡凡",3,"中华田园猫");
Set set=new HashSet();
set.add(huahua);
set.add(fanfan);
//使用迭代器输出集合中的元素
Iterator it=set.iterator();
while(it.hasNext()) {
System.out.println(it.next());
}
}
}
使用迭代器输出时,重写了toString方法。因为it.next()这时输出的输出的是地址。