一、HashSet集合
HashSet集合元素特点:元素唯一,元素无序
HashSet集合在存储元素时,为确保元素的唯一性,在向集合中存入元素时先调用元素对象
的hashCode()方法获取一个对象的哈希值,根据对象的哈希值计算出一个存储位置,再判断该
该位置上是否有元素,没有元素则直接存入元素;有元素,则调用对象的equals()方法比较存入
元素与该位置上的元素,相等就舍弃,不相等就把元素存入。
在实际开发中,需在元素对象所属的类中重写hashCode()方法和equals()方法。具体做法是:
直接在Source双击hashCode()与equals()方法。以上做法实现了HashSet集合元素唯一性的特征
二、TreeSet集合
TreeSet集合元素特点:元素有序,并且元素唯一
TreeSet集合采用二叉树结构来实现元素的排序,并且保证元素唯一
两种方式实现TreeSet排序并且保证元素唯一:
第一种:无参构造,元素对象所属的类实现Comparable接口,并重写compareTo()方法,
第二种:带参构造,比较器接口Comparator,具体理解为:构造方法的参数为接口Comparator,
那么需要定义一个类去实现该接口,并且根据该类进行对象实例化,在该类中重写compare()方法
以上可以采用匿名内部类的做法实现,就是接口的匿名子类对象
具体代码体现:
HashSet:重写hashCode()与equals()方法
public class Student implements Comparable<Student>{
private String name;
private int age;
public Student(String name,int age){
this.name = name;
this.age = age;
}
public String getName(){
return name;
}
public void setName(String name){
this.name =name;
}
public int getAge(){
return age;
}
public void setAge(int age){
this.age =age;
}
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + age;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Student other = (Student) obj;
if (age != other.age)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}
TreeSet:比较器接口Comparator代码
public class MyComparator implements Comparator<Student>{
//重写compare()方法
public int compare(Student s1,Student s2){
//按需求进行的比较
.....
return 0;
}
}
public class TreeSetTest{
public static void main(String[] args){
// MyComparator mc = new MyComparator();
// TreeSet<Student> ts = new TreeSet<Student>(mc);
TreeSet<Student> ts = new TreeSet<Student>(new MyComparator());
//创建元素对象,添加
.....
//遍历集合
.....
}
}
TreeSet:比较器接口Comparator匿名内部类代码
public class TreeSetTest {
public static void main(String[] args) {
//匿名内部类
TreeSet<Student> ts= new TreeSet<Student>(new Comparator<Student>(){
public int compare(Student s1, Student s2) {
按需求进行的比较
.....
return 0;
}
});
//创建元素对象,添加元素
......
//遍历集合
.....
}
}
TreeSet:实现Comparable接口代码
public class Student implements Comparable<Student>{
//标准学生类代码
......
//重写compareTo()方法
public int compareTo(Student s){
//按需求进行的比较
.....
return 0;
}
}