您的位置:首页 > 编程语言 > Java开发

【java】TreeSet的自然排序

2015-01-21 20:31 369 查看
package collection;
/*
* TreeSet的自然排序
* 向TreeSet类对象中添加自定义的类对象,会报错classCastException 类型转换异常 ,因为不能转换成 Comparabel的实现类。
* 步骤:
* 1,自定义类实现Comparable接口       Person implements Comparable
* 2,自定义类除了需要重写hashCode()和equals()方法外,还需要重写compareTo(Object obj)方法,在方法中自定义排序规则。
*/
import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;

import org.junit.Test;

public class TestTreeSet {
public static void main(String[] args) {

}

@Test
public void test1() {
Set ts = new TreeSet();
ts.add(new Person(1001, "张三", 23));
ts.add(new Person(1002, "李四", 24));
ts.add(new Person(1001, "王五", 24));
ts.add(new Person(1001, "aa", 24));
Iterator iterator = ts.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
}

class Person implements Comparable {// 第一步:自定义类必须实现Comparable接口
private int id;
private String name;
private int age;

public Person() {
super();
}

public Person(int id, String name, int age) {
super();
this.id = id;
this.name = name;
this.age = age;
}

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

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 [id=" + id + ", name=" + name + ", age=" + age + "]";
}

@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + age;
result = prime * result + id;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}

@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Person other = (Person) obj;
if (age != other.age)
return false;
if (id != other.id)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}

public int compareTo(Object obj) {// 第二步:重写compareTo()方法,自定义排序规则
Person p = (Person) obj;
int result;
result = id > p.id ? 1 : (id == p.id ? 0 : -1);
if (result == 0) {
result = age > p.age ? 1 : (age == p.age ? 0 : -1);
if (result == 0) {
result = name.compareTo(p.name);
}
}
return result;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息