HashSet 集合存储自定义对象并遍历

package exercise;


import java.util.HashSet;
/*
 * HashSet 集合存储自定义对象并遍历,如果对象的成员遍历值相同即为同一个对象。
 * 它的底层是哈希表结构,而哈希表底层依赖的是hashCode()和equals()方法来保证其唯一性*/


//可以单独写一个具体类H,为了能看清楚写在了同一个页面中。

class H {

private String name;
private int age;
private char sex;


public H() {
super();


}


public H(String name, int age, char sex) {
super();
this.age = age;
this.name = name;
this.sex = sex;
}


@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + age;
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + sex;
return result;
}


@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
H other = (H) obj;
if (age != other.age)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (sex != other.sex)
return false;
return true;
}


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;
}


public char getSex() {
return sex;
}


public void setSex(char sex) {
this.sex = sex;
}


}




public class HistoryDemo {
public static void main(String[] args) {
HashSet<H> hs = new HashSet<H>();


// 创建历史任务对象
H h1 = new H("秦桧", 25, '男');
H h2 = new H("秦桧", 25, '男');
H h3 = new H("秦桧", 23, '男');
H h4 = new H("秦琼", 25, '男');
H h5 = new H("高俅", 25, '女');
H h6 = new H("高俅", 25, '男');
H h7 = new H("秦桧", 25, '男');


hs.add(h1);
hs.add(h2);
hs.add(h3);
hs.add(h4);
hs.add(h5);
hs.add(h6);
hs.add(h7);


// 遍历
for (H h : hs) {
System.out.println(h.getAge() + "----" + h.getName() + "------" + h.getSex());
}


}

}

运行:


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值