容器类HashSet和TreeSet习题

来源:互联网 发布:个性主题下载软件 编辑:程序博客网 时间:2024/06/05 11:06

使用HashSetTreeSet存储多个商品信息,遍历并输出;其中商品属性:编号,名称,单价,出版社;要求向其中添加多个相同的商品,验证集合中元素的唯一性。
提示:向HashSet中添加自定义类的对象信息,需要重写hashCodeequals( )
 TreeSet中添加自定义类的对象信息,需要实现Comparable接口,指定比较规则



TreeSet


import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.TreeSet;




public class Goodss implements Comparable<Goodss>{
int bh;
String name;
double much;
String work;
public Goodss(int bh, String name, double much, String work) {
this.bh = bh;
this.name = name;
this.much = much;
this.work = work;
}
public static void main(String[] args) {
Goodss a = new Goodss(1, "钢铁是怎样练成的", 12.5, "小日本出版社");
Goodss a1 = new Goodss(2, "坏蛋是怎样练成的", 15.0, "小台湾出版社");
Goodss a2 = new Goodss(3, "天才是怎样练成的", 20.5, "小美国出版社");
Goodss a3 = new Goodss(3, "天才是怎样练成的", 20.5, "小美国出版社");
TreeSet<Goodss> ttw = new TreeSet<Goodss>();
ttw.add(a);
ttw.add(a1);
ttw.add(a2);
ttw.add(a3);
for(Goodss r:ttw){
System.out.println(r.name+"\t"+r.work+"\t"+r.bh+"\t"+r.much);
}

}



@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + bh;
long temp;
temp = Double.doubleToLongBits(much);
result = prime * result + (int) (temp ^ (temp >>> 32));
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((work == null) ? 0 : work.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Goodss other = (Goodss) obj;
if (bh != other.bh)
return false;
if (Double.doubleToLongBits(much) != Double
.doubleToLongBits(other.much))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (work == null) {
if (other.work != null)
return false;
} else if (!work.equals(other.work))
return false;
return true;
}


@Override
public int compareTo(Goodss o) {
if(this.bh>o.bh){
return 1;

}if(this.bh<o.bh){
return -1;
}
return 0;
}




}
原创粉丝点击