import java.util.*;
/*
Set:无序,不可以重复元素。
|--hashSet:数据结构是哈希表。线程是非同步的。
保证元素唯一性的原理:判断元素的哈希值是否相同。
如果相同,还会继续判断元素的equals方法。是否为true。
|--TreeSet:可以对Set中的元素进行排序。
底层数据结构是二叉树。
保证元素唯一性依据:
compareTo方法return 0;
TreeSet排序的第一种方式:让元素具有比较性,
元素需要实现Comparable接口,覆盖compareTo方法。
这种方式也称为自然顺序,或者叫做默认顺序。
TreeSet的第二种排序方式:
当元素不具备比较性时,或者具备的比较性不是所需要的。
这时就需要让集合具有比较性,
在集合初始化时,就有了比较方式。
需求:往TreeSet集合中存储自定义学生对象。
按照学生的年龄进行排序。
排序时,当主要条件相同时,一定要判断一次次要条件。
*/
class TreeSetDemo
{
public static void main(String[] args)
{
TreeSet ts = new TreeSet();
ts.add(new Student("xiaoli01",20));
ts.add(new Student("xiaoli02",22));
ts.add(new Student("xiaoli03",23));
ts.add(new Student("xiaoli06",24));
ts.add(new Student("xiaoli05",24));
Iterator it = ts.iterator();
while(it.hasNext())
{
Student stu =(Student)it.next();
sop(stu.getName()+"----"+stu.getAge());
}
}
public static void sop(Object obj)
{
System.out.println(obj);
}
}
class Student implements Comparable//该接口强制学生具有比较性
{
private String name;
private int age;
public static void sop(Object obj)
{
System.out.println(obj);
}
Student(String name,int age)
{
this.name = name;
this.age = age;
}
public int compareTo(Object obj)
{
//当返回值为0时,之存入一个元素。
return 0;
//按存入的逆序输出
//return -1;
//怎么存入怎么输出
//return 1;
/*if(!(obj instanceof Student))
throw new RuntimeException("不是学生");
Student s = (Student)obj;
sop(this.getName()+"....compareTo..."+s.getName());
if(this.age>s.age)
return 1;
if(this.age==s.age)
return this.name.compareTo(s.name);
return -1;*/
}
// public void setName(String name )
// {
// this.name = name;
// }
// public void setAge(int age)
// {
// this.age = age;
// }
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
}