Set集合不允许重复;
HashSet:无序
TreeSet:有序,使用的是一个升序排列。
使用TreeSet集合装对象的时候,该对象必须实现Comparable接口,覆写comparTo()方法,TreeSet集合实现排序,通过comparTo()方法,所以属性都参加比较。
代码细节:
简单Java类实现Comparable接口
package cn14.Set;
public class Person implements Comparable<Person>{
private String name;
private Integer age;
public Person() {
super();
// TODO Auto-generated constructor stub
}
public Person(String name, int age) {
super();
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 String toString() {
return "Person [name=" + name + ", age=" + age + "]";
}
@Override
public boolean equals(Object obj) {
Person p=(Person)obj;
if(obj==null){
return false;
}
if(obj==this){
return true;
}
if(this.name.equals(p.name)&&this.age.equals(p.age)){
return true;
}
return false;
}
@Override
public int compareTo(Person p) {
if(p.age>this.age){
return 1;
}else if(p.age<this.age){
return -1;
}else{
return this.name.compareTo(p.name);
}
}
}
测试类TreeSet
package cn14.Set;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;
public class TestTreeSet {
public static void main(String []args){
Set<Person> li=new TreeSet<Person>();
li.add(new Person("张三",18));
li.add(new Person("张",18));
li.add(new Person("王五",68));
li.add(new Person("小胖",35));
System.out.println(li);
Iterator<Person> it=li.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
}
}