标签:
1 import java.util.Comparator; 2 import java.util.Iterator; 3 import java.util.TreeSet; 4 5 6 public class Test2 7 { 8 public static void main(String[] args) 9 { 10 TreeSet<Person> set = new TreeSet<>(new Comparator<Person>() { 11 12 @Override 13 public int compare(Person o1, Person o2) 14 { 15 int result; 16 result = o1.getAge()-o2.getAge(); 17 if(result==0) { 18 result = o1.getName().compareTo(o2.getName()); 19 } 20 return result; 21 } 22 }); 23 Person p1 = new Person("剑魔",20); 24 Person p2 = new Person("剑姬",20); 25 Person p3 = new Person("剑豪",20); 26 Person p4 = new Person("剑圣",20); 27 set.add(p1); 28 set.add(p2); 29 set.add(p3); 30 set.add(p4); 31 Iterator<Person> iterator = set.iterator(); 32 while(iterator.hasNext()) { 33 System.out.println(iterator.next()); 34 } 35 } 36 }
自定义一个类
1 public class Person 2 { 3 private String name; 4 private int age; 5 public String getName() 6 { 7 return name; 8 } 9 public void setName(String name) 10 { 11 this.name = name; 12 } 13 public int getAge() 14 { 15 return age; 16 } 17 public void setAge(int age) 18 { 19 this.age = age; 20 } 21 public Person(String name, int age) 22 { 23 super(); 24 this.name = name; 25 this.age = age; 26 } 27 public Person() 28 { 29 super(); 30 } 31 @Override 32 public String toString() 33 { 34 return "Person [name=" + name + ", age=" + age + "]"; 35 } 36 @Override 37 public int hashCode() 38 { 39 final int prime = 31; 40 int result = 1; 41 result = prime * result + age; 42 result = prime * result + ((name == null) ? 0 : name.hashCode()); 43 return result; 44 } 45 @Override 46 public boolean equals(Object obj) 47 { 48 if (this == obj) 49 return true; 50 if (obj == null) 51 return false; 52 if (getClass() != obj.getClass()) 53 return false; 54 Person other = (Person) obj; 55 if (age != other.age) 56 return false; 57 if (name == null) 58 { 59 if (other.name != null) 60 return false; 61 } 62 else if (!name.equals(other.name)) 63 return false; 64 return true; 65 } 66 67 }
标签:
原文地址:http://www.cnblogs.com/Riven/p/4658965.html