set集合添加元素的源码:
根据需求实现一些排序,先按价钱,再按数量进行排序....当出现两个“pingguo”时候,他们hashcode是相同的,但是如果只重新hashcode 不重写equals set集合仍可以添加进去
public class Te {
public static void main(String[] args) {
ArrayList<pro> list=new ArrayList<pro>();
pro p=new pro("pinguo", 12, 214);
pro p1=new pro("pinguo", 11, 214);
pro p2=new pro("xiangjiao",11,213);
list.add(p);
list.add(p1);
list.add(p2);
Collections.sort(list, new Comparator<pro>() {
public int compare(pro o1, pro o2) {
if(o1.getPrice()>o2.getPrice()) return 1;
else if(o1.getPrice()==o2.getPrice()&&o1.getNumber()>o2.getNumber()) return 1;
return -1;
}
});
/* for (pro pro : list) {
System.out.println(pro);
}*/
Set<pro> set=new HashSet<pro>();
set.add(p);
set.add(p1);
set.add(p2);
for (pro pro : set) {
System.out.println(pro);
}
}
}
重写hashcode和equals 来 判断set集合添加元素是否重复。
public class pro {
private String name;
private double price;
private int number;
public pro() {
super();
// TODO Auto-generated constructor stub
}
public pro(String name, double price, int number) {
super();
this.name = name;
this.price = price;
this.number = number;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
@Override
public int hashCode() {
return this.getName().hashCode();
}
@Override
public boolean equals(Object obj) {
if(obj instanceof pro){
pro p=(pro) obj;
return p.getName().equals(this.getName());
}
return false;
}
/* @Override
public String toString() {
return "pro [name=" + name + ", price=" + price + ", number=" + number
+ "]";
}*/
}