------- <a href="http://www.itheima.com" target="blank">android培训</a>、<a href="http://www.itheima.com" target="blank">java培训</a>、期待与您交流! ----------
1. Set:无序,不可以重复元素。
TreeSet:可以对Set集合中的元素进行排序。
排序时,当主要条件相同时,一定判断次要条件。
例子:
class TreeSetDemo
{
public static void main(String[] args)
{
TreeSet ts = new TreeSet();
ts.add(new Student("Lisi02",22));
ts.add(new Student("Lisi007",20));
ts.add(new Student("Lisi09",19));
ts.add(new Student("Lisi01",40));
Iterator it = ts.iterator();
while(it.hasNext())
{
Student stu = (Student)it.next();
System.out.println(stu.getName()+"....."+stu.getAge());
}
}
}
class Student implements Comparable//该接口强制让学生具备比较性
{
private String name;
private int age;
Student(String name,int age)
{
this.name = name;
this.age = age;
}
public int compareTo(Object obj)
{
if(!(obj instanceof Student))
{
throw new RuntimeException("不是学生对象");
}
Student s = (Student)obj;
if(this.age>s.age)
{
return 1;
}
if(this.age==s.age)
{
return this.name.compareTo(s.name);
}
return -1;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
}
2. TreeSet排序的第一种方式:让元素自身具有比较性,元素需要实现Comparable接口,覆 盖CompareTo方法,这种方式也成为元素的自然排序,或者叫做默认顺序。
3. TreeSet的第二种排序方式,当元素自身不具备比较性时,或者具备的比较性不是所需要 的,这时就需要让集合自身具备比较性。在集合初始化时,就具备啦比较性。
例子:
class Mycompatre implements Comparator
{
public int compare(Object o1,Object o2)
{
Student s1 = (Student)o1;
Student s2 = (Student)o2;
int num = s1.getName().compareTo(s2.getName());
if(num==0)
{
if(s1.getAge()>s2.getAge())
{
return 1;
}
if(s1.getAge()==s2.getAge())
{
return 0;
}
return -1;
}
return num;
}
}
class TreeSetDemo
{
public static void main(String[] args)
{
TreeSet ts = new TreeSet(new MyCompare);
ts.add(new Student("Lisi02",22));
ts.add(new Student("Lisi007",20));
ts.add(new Student("Lisi09",19));
ts.add(new Student("Lisi01",40));
Iterator it = ts.iterator();
while(it.hasNext())
{
Student stu = (Student)it.next();
System.out.println(stu.getName()+"....."+stu.getAge());
}
}
}
当两种排序都存在时,以比较器为主,定义一个类,实现Comparator接口,覆盖compare 方法。
4. 学习心得体会:
熟悉框架的各种方法,掌握TreeSe的两种的创建方法,
------- <a href="http://www.itheima.com" target="blank">android培训</a>、<a href="http://www.itheima.com" target="blank">java培训</a>、期待与您交流! ----------