Set属于Collection集合的子接口
Set集合有两个重要的子接口:HashSet和TreeSet
HashSet:(使集合保持不重复,无序的状态)向HashSet中加元素时,首先会检查hashCode,如果一致,才会调用equals方法,如果相等,才会认为两个对象相等,这时集合会认为新加入的对象已经存在(需重写hashCode和equals方法,自己可以定规则)
TreeSet:(在防止重复上和HashSet是一样的,但它会一直保持集合处于有序的状态)要使用TreeSet,集合中的元素必须是实现Comparable的类型,实现了Comparable,就必须得重写compareTo()方法,否则再加入第二个元素时,会因为无法调用对象的compareTo()而失败
例如以下几段代码是我在写商品类时重写的方法
1)、重写hashCode方法
//因为所有的商品数据在set集合中,需要重写hashCode @Override public int hashCode() {
//加入的商品以其规则判断hashCode值是否相等
return this.id.hashCode()*31+this.name.hashCode()*13; }
2)、 重写equals方法
//商品的编号一致就是同一个商品 public boolean equals(Object obj) { if(obj==this)return true; if(obj instanceof Product) { Product p=(Product)obj; return p.id.equals(this.id); } return false; }
3)、重写compareTo()方法
@Override public int compareTo(Product o) { //针对0 if(o.date.equals(this.date))return -1;//一样的随便排 //正数和负数 return this.date.compareTo(o.date);//以比较日期比较两个对象的大小,比较的是ASCII值
}