日期:2014-05-20 浏览次数:20783 次
import java.util.Set;
import java.util.TreeSet;
class Person implements Comparable<Person>{
private String name;
private int age;
public Person(String name,int age){
this.name=name;
this.age=age;
}
public String toString(){
return "姓名:"+this.name+" 年龄:"+this.age;
}
public int compareTo(Person per){
if(this.age>per.age){
return 1;
}else if(this.age==per.age){
return 0;
}else{
return -1;
}
}
}
public class SetDemo03{
public static void main(String args[]){
Set<Person> allSet=new TreeSet<Person>();
allSet.add(new Person("张三",22));
allSet.add(new Person("李四",23));
allSet.add(new Person("王五",21));
allSet.add(new Person("王五",21));
allSet.add(new Person("王五",21));
allSet.add(new Person("赵六",32));
allSet.add(new Person("孙七",11));
System.out.println(allSet);
}
}
import java.util.Arrays;
class AlohaPerson implements Comparable<AlohaPerson> {
private String name;
AlohaPerson(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return name;
}
@Override
public int compareTo(AlohaPerson o) {
return this.name.compareTo(o.name);
}
}
public class Aloha {
public static void sort(AlohaPerson[] persons) {
// 用选择排序法排序
for (int i = 0; i < persons.length - 1; ++i) {
int k = i;
for (int j = k; j < persons.length; ++j) {
// 排序的时候在比较两个对象时用compareTo方法.
if (persons[j].compareTo(persons[k]) < 0) {
k = j;
}
}
if (k != i) {
AlohaPerson temp = persons[k];
persons[k] = persons[i];