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

来源:互联网 发布:阿里云创建快照 编辑:程序博客网 时间:2024/06/07 03:05
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");}}@Overridepublic 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;}@Overridepublic 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
原创粉丝点击