使用HashSet方法实现多个对象的遍历

package com.zuoye;

import java.util.HashSet;

public class Goods {
	int num;
	String name;
	double price;
	String press;
	public Goods(int num, String name, double price, String press) {
		this.num = num;
		this.name = name;
		this.price = price;
		this.press = press;
	}
	public static void main(String[] args) {
		Goods g1=new Goods(1, "JAVA", 80.9, "清华大学出版社");
		Goods g2=new Goods(2, "JSP", 45.8, "浙江大学出版社");
		Goods g3=new Goods(3, "PHP", 56, "北京大学出版社");
		Goods g4=new Goods(4, "SSH", 79, "复旦大学出版社");
		Goods g5=new Goods(2, "JSP", 45.8, "浙江大学出版社");
		Goods g6=new Goods(4, "SSH", 79, "复旦大学出版社");
		HashSet<Goods> hs = new HashSet<Goods>();
		hs.add(g1);
		hs.add(g2);
		hs.add(g3);
		hs.add(g4);
		hs.add(g5);
		hs.add(g6);
		for(Goods g:hs){
			System.out.println(g.num+"\t"+g.name+"\t"+g.price+"\t"+g.press+"\t");
		}
		
	}
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((press == null) ? 0 : press.hashCode());
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		result = prime * result + num;
		long temp;
		temp = Double.doubleToLongBits(price);
		result = prime * result + (int) (temp ^ (temp >>> 32));
		return result;
	}
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Goods other = (Goods) obj;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		if (num != other.num)
			return false;
		if (press == null) {
			if (other.press != null)
				return false;
		} else if (!press.equals(other.press))
			return false;
		if (Double.doubleToLongBits(price) != Double
				.doubleToLongBits(other.price))
			return false;
		return true;
	}

}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值