存储的对象是无序的(集合中存储对象的顺序和使用add方法添加对象的顺序不一),存储的对象是不可以重复的
没有特有的方法
HashSet
- 后缀:Set,说明存储的数据无序,不可以存储相同的对象
- 前缀:Hash,说明该集合在存储数据时底层数据结构使用的是哈希表(数组+链表)
- 在使用add方法添加元素时,已经保证了元素的唯一
- 当向集合添加对象时,把要添加的对象和集合中已有的对象比较哈希值,如果和集合中所有对象的哈希值都不相同,则直接加入集合,如果和集合中已有的对象存在哈希值相同的,那么并不认为是同一个对象,还会调用equals方法,确定是否是同一个对象,如果equals方法返回true,则最终认为是同一个对象,不加入集合,返回false,则认为不是同一个对象,使用链表链接在后面。
- 为什么无序?因为元素的存储位置是根据哈希算法计算出来的
- 保证元素唯一的原理: int hashCode( ) boolean equals(0bject obj)
姓名年龄相同的认为是同一个对象:重写hashCode和equals方法
class Student{
………………
public int hashCode(){
return name.hashCode()+age*36;
}
public boolean equals(Object obj){
if(!(obj instanceof Student))
throw new ClassCastException("类型不对");
Student stu=(Student)obj;
return this.name.equals(stu.name)&&this.age==stu.age;
}
}
TreeSet
- 后缀:Set,说明存储的数据无序,不可以存储相同的对象
- 前缀:Tree,说明该集合在存储数据时底层数据结构使用的是二叉树
- 具备排序功能
- 加入到集合中的对象必须具备比较大小的功能,需要让对象所属的类实现Comparable接口中的int compareTo()方法
- 因为排序了所以导致了无序
- compareTo方法的返回值为0,则认为是同一个对象,不加入集合,从而保证了加入集合的对象唯一
- 当对象默认的比较方式不符合我们的需求,可以自定义比较大小的方式
自定义比较方式必须实现Comparator接口中的int compare (Obejct obj1 , Object obj2) 方法,优先使用自定义的比较方法
让对象所属的类实现Comparable接口中的int compareTo()方法
class Student implements Comparable{
………………
public int compareTo(Object obj){
if(!(obj instanceof Student))
throw new ClassCastException("类型不对");
Student stu=(Student)obj;
int num = this.age-stu.age;
return num==0?name.compareTo(stu.name):num;
}
}
自定义比较方式必须实现Comparator接口中的int compare (Obejct obj1 , Object obj2) 方法
class ComByLength implements Comparator{
public int compare(Object obj1,Object obj2{
if(!(obj1 instanceof String))
throw new ClassCastException("类型不对");
if(!(obj2 instanceof String))
throw new ClassCastException("类型不对");
String str1=(String)obj1;
String str2=(String)obj2;
return str1.length()-str2.length();//从短到长
}
}
class Demo10{
public static void main(String[] args){
ComByLength comByLength=new ComByLength();
TreeSet ts = new TreeSet(comByLength);
//优先使用自定义比较方式
ts.add("wangyuyuyuyuyuyuyu"); //String Comparable
ts.add("chen");
ts.add("yan");
ts.add("sunxuxuxu");
System.out.println(ts);
}
}
- TreeSet(Collection<? extends E> c)
TreeSet<Student> st1=new TreeSet<>();
st1.add(new Student("lisi",20));
st1.add(new Student("zhaosi",22));
TreeSet<Worker> st2=new TreeSet<>();
st2.add(new Worker("xiaobai",28));
st2.add(new Worker("zhaoliu",29));
TreeSet<Person> ts = new TreeSet<>(st1);
TreeSet<Person> ts = new TreeSet<>(st2);
- **TreeSet(Comparator<? super E> comparator) **
class ComByNames implements Comparator<Person>{
public int compare(Person w1,Person w2){
return w1.getName().compareTo(w2.getName());
}
}
class Demo8 {
public static void main(String[] args) {
ComByNames comByNames=new ComByNames();
TreeSet<Student> st1=new TreeSet<>(comByNames);
st1.add(new Student("lisi",20));
st1.add(new Student("zhaosi",22));
st1.add(new Student("wangwu",18));
TreeSet<Worker> st2=new TreeSet<>(comByNames);
st2.add(new Worker("xiaobai",28));
st2.add(new Worker("zhaoliu",29));
st2.add(new Worker("wangwu",16));
}
}