Java之泛型练习

package cn.itcast.generics;

import java.util.Comparator;
import java.util.Iterator;
import java.util.TreeSet;

/*
 * 方法一:实现Comparable接口
 */
//class Person implements Comparable<Person> {//实现Comparable接口,使得集合元素具备可比较性
// String name;
// int age;
//
// 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 int compareTo(Person p) {//复写Comparable的compareTo()方法
////  Person p = (Person) o;
//  /*
//   * 按年龄进行比较
//   */
////        int temp=this.age-p.age;
////        return temp==0?this.getName().compareTo(p.getName()):temp;
//  /*
//   * 按姓名进行比较
//   */
//  int temp=this.getName().compareTo(p.getName());
//  return temp==0?this.age-p.age:temp;
// }
//
//}
/*
 * 方法2:实现Comparator接口,覆盖compare()方法,
 * 并且将该类对象作为实际参数传递给TreeSet集合的构造函数
 */
class Person implements Comparator<Person>{
 String name;
 int age;
 
 public Person() {
  
 }
 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 int compare(Person o1, Person o2) {
  int temp=o1.getName().compareTo(o2.getName());
  return temp==0?o1.getAge()-o2.getAge():temp;
 }
}

public class GenericDemo2 {
 /**
  * @param args
  */
 public static void main(String[] args) {

  TreeSet<Person> p = new TreeSet<Person>(new Person());
  p.add(new Person("lisi", 21));
  p.add(new Person("ahangsan", 42));
  p.add(new Person("wangwu", 21));
  p.add(new Person("buliu", 34));
  p.add(new Person("xuliu", 26));
  Iterator<Person> it = p.iterator();
  while (it.hasNext()) {
   Person p2 = it.next();
   System.out.println(p2.getName() + ":::" + p2.getAge());
  }
 }

}

 

posted @ 2016-03-12 22:11  菜鸟奋斗史  阅读(932)  评论(0编辑  收藏  举报