容器作业

来源:互联网 发布:网络与新媒体就业方向 编辑:程序博客网 时间:2024/09/21 09:28

1. 使用HashSetTreeSet存储多个商品信息,遍历并输出;其中商品属性:编号,名称,单价,出版社;要求向其中添加多个相同的商品,验证集合中元素的唯一性。

提示:向HashSet中添加自定义类的对象信息,需要重写hashCodeequals( )

 TreeSet中添加自定义类的对象信息,需要实现Comparable接口,指定比较规则

public class Goods implements Comparable<Goods> {String name;String number;Double price;String press;public Goods(String name, String number, Double price, String press) {this.name = name;this.number = number;this.price = price;this.press = press;}@Overridepublic int hashCode() {final int prime = 31;int result = 1;result = prime * result + ((name == null) ? 0 : name.hashCode());result = prime * result + ((number == null) ? 0 : number.hashCode());result = prime * result + ((press == null) ? 0 : press.hashCode());result = prime * result + ((price == null) ? 0 : price.hashCode());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 (number == null) {if (other.number != null)return false;} else if (!number.equals(other.number))return false;if (press == null) {if (other.press != null)return false;} else if (!press.equals(other.press))return false;if (price == null) {if (other.price != null)return false;} else if (!price.equals(other.price))return false;return true;}@Overridepublic String toString() {return "Goods [name=" + name + ", number=" + number + ", price="+ price + ", press=" + press + "]";}@Overridepublic int compareTo(Goods o) {if (o.price < price) {return 1;}if (o.price > price) {return -1;}return 0;}}
public class HashSetDemo {public static void main(String[] args) {Goods g1 = new Goods("面包", "1111", 12.0, "河南");Goods g2 = new Goods("啤酒", "1123", 10.0, "河南");Goods g3 = new Goods("啤酒", "1123", 10.0, "河南");Goods g4 = new Goods("瓜子", "1131", 8.0, "河南");Goods g5 = new Goods("面包", "1111", 12.0, "河南");HashSet<Goods> h = new HashSet<Goods>();h.add(g1);h.add(g2);h.add(g3);h.add(g4);h.add(g5);for (Goods k : h) {System.out.println(k.toString());}}}
public class TreeSetDemo {private static final String Goods = null;public static void main(String[] args) {Goods g1 = new Goods("面包", "1111", 12.0, "河南");Goods g2 = new Goods("啤酒", "1123", 10.0, "河南");Goods g3 = new Goods("啤酒", "1123", 10.0, "河南");Goods g4 = new Goods("瓜子", "1131", 8.0, "河南");Goods g5 = new Goods("面包", "1111", 12.0, "河南");TreeSet<Goods> t = new TreeSet<Goods>();t.add(g1);t.add(g2);t.add(g3);t.add(g4);t.add(g5);for (Goods j : t) {System.out.println(j);}}}


原创粉丝点击