treeSet
构造方法摘要 | |
---|---|
TreeSet() 构造一个新的空 set,该 set 根据其元素的自然顺序进行排序。 | |
TreeSet(Collection<? extends E> c) 构造一个包含指定 collection 元素的新 TreeSet,它按照其元素的自然顺序进行排序。 | |
TreeSet(Comparator<? super E> comparator) 构造一个新的空 TreeSet,它根据指定比较器进行排序。 | |
TreeSet(SortedSet<E> s) 构造一个与指定有序 set 具有相同映射关系和相同排序的新 TreeSet。 |
接口 Comparator<T>
方法摘要 | |
---|---|
int | compare(T o1, T o2) 比较用来排序的两个参数。 |
boolean | equals(Object obj) 指示某个其他对象是否“等于”此 Comparator。 |
package com.Set;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Iterator;
import java.util.TreeSet;
import javax.management.RuntimeErrorException;
/**
*
* @author 小明
* 往TreeSet集合中存储自定义对象学生;想按照学生的年龄进行排序
* 底层数据结构是二叉树:
* 保证元素的唯一性是compareTo()方法 return 0
*/
//这里比较姓名 根据姓名排序
class MyComparator implements Comparator{
@Override
public int compare(Object o1, Object o2) {
Student2 s1 = (Student2) o1;
Student2 s2 = (Student2) 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 new Integer(s1.getAge()).compareTo(new Integer(s2.getAge()));
}
return num;
}
}
class Student2 implements Comparable{//该接口强制比较性
private String name;
private int age;
Student2(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;
}
@Override
public boolean equals(Object obj) {
if(!(obj instanceof Student)){
return false;
}
Student2 p = (Student2) obj;
System.out.println(this.name+"-equals--"+p.name);
return this.name.equals(p.name) && this.age==p.age;
}
@Override
public int hashCode() {
System.out.println(this.name+"...hashcode...");
//return 60;
return name.hashCode()+age;
}
@Override
public int compareTo(Object obj) {
if(!(obj instanceof Student)){
throw new RuntimeException("不是学生") ;
}
Student2 s = (Student2) obj;
System.out.println(this.name +" comp.."+s.name);
if(this.age >s.age){
return 1;
}
if(this.age==s.age){
return this.name.compareTo(s.name);
}
return -1;
}
}
public class TreeSetComparator {
public static void main(String[] args) {
TreeSet<Student2> hs = new TreeSet<Student2>(new MyComparator());
hs.add(new Student2("zhangsan", 20));
hs.add(new Student2("lisi", 30));
hs.add(new Student2("lisi01", 40));
hs.add(new Student2("xiao", 50));
hs.add(new Student2("xiao", 52));
hs.add(new Student2("xiao003", 50));
hs.add(new Student2("xiao001", 50));
Iterator<Student2> iterator = hs.iterator();
while(iterator.hasNext()){
Student2 p = iterator.next();
System.out.println(p.getName()+" "+p.getAge());
}
}
}