Set也是一个接口,继承自Collection,Set有一个特殊的性质:不保存重复的元素。那么它是如何界定重复与否呢?通过对象的euquals()方法确定元素的唯一性。对于部分Set的子类如HashSet和LinkedHashSet由于通过哈希码实现快速查找,所以需重写hashCode()方法。对于TreeSet而言,为了实现排序所以元素需要实现Compareble接口。
我们先来看看java集合给我们提供的set类。
-
import java.util.*;
-
-
public class Main {
-
public static void main(String[] args) {
-
Main sample = new Main();
-
String s = "zhongguoren";
-
Set<Character> hashSet = new HashSet<Character>();
-
Set<Character> linkedHashSet = new LinkedHashSet<>();
-
Set<Character> treeSet = new TreeSet<>();
-
for(int i=0;i<s.length();i++){
-
hashSet.add(s.charAt(i));
-
linkedHashSet.add(s.charAt(i));
-
treeSet.add(s.charAt(i));
-
}
-
System.out.println(hashSet);
-
System.out.println(linkedHashSet);
-
System.out.println(treeSet);
-
}
-
}
输出结果:
由结果可以看出首先输出里都没有重复字符,即set的特性不保存重复的元素。我们还可以看到LinkedHashSet是按元素的插入顺序保存数据的,而HashSet和TreeSet元素的顺序都发生了改变。就性能而言,HashSet和LinkedHashSet都是通过hashcode进行查找,快速查找效率较高,而TreeSet为我们给元素排序提供了方便。
-
import java.util.*;
-
-
public class Main {
-
public static void main(String[] args) {
-
Set<Student> treeSet = new TreeSet<>();
-
Student[] stu = new Student[5];
-
stu[0]=new Student("wang",70);
-
stu[1]=new Student("li", 80);
-
stu[2]=new Student("zhang",70);
-
stu[3]=new Student("zhao", 90);
-
stu[4]=new Student("sun", 90);
-
for(int i=0;i<5;i++){
-
treeSet.add(stu[i]);
-
}
-
System.out.println(treeSet);
-
}
-
}
-
-
class Student implements Comparable<Student>{
-
String name;
-
int score;
-
@Override
-
public int compareTo(Student o) {
-
// TODO Auto-generated method stub
-
if(this.equals(o))
-
return this.score-o.score;
-
else
-
return this.score>=o.score?1:-1;
-
}
-
-
public Student(String name,int score){
-
this.name=name;
-
this.score=score;
-
}
-
-
public String toString(){
-
return name+" "+score;
-
}
-
-
public boolean equals(Object o){
-
return o instanceof Student && this.name.equals(((Student)o).name) && this.score==((Student)o).score;
-
}
-
}
输出结果:
[wang 70, zhang 70, li 80, zhao 90, sun 90]
可以看到Student类实现了comparable接口,TreeSet就是依据compareTo方法进行排序的,同时我重写了equals()方法。值得注意的一点是当我把compareTo方法直接改成return
this.score-o.score后得到的输出结果为[wang 70, li 80, zhao 90]。由此可以看出TreeSet的去重复元素不仅仅是依赖于equals方法,还依赖于compareTo,当两个元素由此方法得到的结果为0时也被视为元素相等。文档中对该方法的介绍有这么一句: * <p>It is strongly recommended, but <i>not</i> strictly required that
* <tt>(x.compareTo(y)==0) == (x.equals(y))</tt>. Generally speaking, any
* class that implements the <tt>Comparable</tt> interface and violates
* this condition should clearly indicate this fact. The recommended
* language is "Note: this class has a natural ordering that is
* inconsistent with equals."
同样HashSet判断元素的不重复也跟hashCode()方法有关。
阅读(1138) | 评论(0) | 转发(0) |