您的位置:首页 > 其它

HashSet与TreeSet去重的区别

2016-08-21 16:31 162 查看
一、HashSet

在HashSet去重是根据Hash码是否相同,即对应两个对象的内存地址是否相同,如果一个对象要去重,要重写HashSet中的equals和hashCode方法

例子:

public class Book {
private String name;
private double price;

public Book(String name, double price) {
this.name = name;
this.price = price;
}

@Override
public String toString() {
return "Book [name=" + name + ", price=" + price + "]";
}

public static void main(String[] args) {
HashSet<Book> hash = new HashSet<Book>();
hash.add(new Book("java开发", 80.9));
hash.add(new Book("java开发", 80.9));
// 输出hashset,两本都存在了hashset中
for (Book s : hash) {
System.out.println(s);
}

}

}


结论:没重写equals 和 hashCode方法时,两本书名和价格一样的书都存入了hashset中

重写equals方法和hashCode方法后:

public class Book {
private String name;
private double price;

public Book(String name, double price) {
this.name = name;
this.price = price;
}
//-------------------------------------------------
//重写的hashCode和equals方法,在eclipse--Source中可以自动生成这两个方法
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
long temp;
temp = Double.doubleToLongBits(price);
result = prime * result + (int) (temp ^ (temp >>> 32));
return result;
}

@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Book other = (Book) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (Double.doubleToLongBits(price) != Double.doubleToLongBits(other.price))
return false;
return true;
}
//--------------------------------------------------

@Override
public String toString() {
return "Book [name=" + name + ", price=" + price + "]";
}

public static void main(String[] args) {
HashSet<Book> hash = new HashSet<Book>();

hash.add(new Book("java开发", 80.9));
hash.add(new Book("java开发", 80.9));
// 输出hashset,只有一本书存在了hashSet中
for (Book s : hash) {
System.out.println(s);
}

}

}


结论:重写了equals 和 hashCode方法后,只有一本书存在了hashSet方法中

二、TreeSet

TreeSet去重是根据二叉树原理,根据比较器设置的比较属性去重

例子:

public class Book implements Comparable<Book> {
private String name;
private double price;

public Book(String name, double price) {
this.name = name;
this.price = price;
}

@Override
public String toString() {
return "Book [name=" + name + ", price=" + price + "]";
}

// 重写比较器中的compare方法,按照书名来排序
@Override
public int compareTo(Book o) {
return this.name.compareTo(o.name);
}

public static void main(String[] args) {
TreeSet<Book> hash = new TreeSet<Book>();
hash.add(new Book("ja
4000
va开发", 80.9));
hash.add(new Book("java开发", 80.9));// 同名同价格
hash.add(new Book("java开发", 20.1));// 同名不同价格
hash.add(new Book("Android开发", 80.9));// 不同名同价格
// 输出Treeset
for (Book s : hash) {
System.out.println(s);
}
/*
* 输出结果:同名的书都去重了
* Book [name=Android开发, price=80.9]
* Book [name=java开发,price=80.9]
*/

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Set集合框架