TreeSet 集合的特点:
1.它是Set集合的一种 就是无角标型的,二分叉的数据结构
2.它是按照CompareTo()来有序地存放数据的
3.它可以依赖2中比较方式,一种是比较器,一种Comperable;
4.比较器可以随便定义主要比较方法,而Comperable是要格局特定的需求更改的
-------------------------------------------------------------------------------------------
package com.java.TreeSetDmeo.www;
import java.util.Comparator;
import java.util.Iterator;
import java.util.TreeSet;
import com.java.b.www.ComstorByName;
import com.java.b.www.Soilder;
public class TreeSetDmeo {
public static void main(String[] args) {
TreeSet set=new TreeSet(new ComstorByName());
set.add(new Soilder("lisi1",27));
set.add(new Soilder("lisi8",21));
set.add(new Soilder("lisi9",23));
set.add(new Soilder("lisi9",25));
set.add(new Soilder("lisi15",15));
for (Iterator it = set.iterator(); it.hasNext();) {
System.out.println(it.next());
}
}
}
package com.java.b.www;
import java.util.Comparator;
public class Soilder {
private String name;
private int age;
public Soilder(String name, int age) {
super();
this.name = name;
this.age = age;
}
public Soilder() {
super();
}
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;
}
@Override
public String toString() {
return "Soilder [name=" + name + ", age=" + age + "]";
}
/*@Override
public int compareTo(Object obj){
Soilder s=(Soilder)obj;
return this.age-s.age;
}*/
}
package com.java.b.www;
import java.util.Comparator;
import com.java.b.www.Soilder;;
public class ComstorByName implements Comparator{
public int compare(Object o, Object o1) {
Soilder stu1=(Soilder)o;
Soilder stu2=(Soilder)o1;
int temp=stu1.getName().compareTo(stu2.getName());
if(temp>0){
return temp;
}
if(temp<0){
return temp;
}
return stu1.getAge()-stu2.getAge();
}
}