• 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());
      }
     }
    
    }
  • 相关阅读:
    【BZOJ】1552/3506 [Cerc2007]robotic sort
    【BZOJ】1014 [JSOI2008]火星人prefix
    【BZOJ】1500: [NOI2005]维修数列
    【51NOD-0】1046 A^B Mod C
    【51NOD-0】1019 逆序数
    【51NOD-0】1018 排序
    【51NOD-0】1012 最小公倍数LCM
    The Grove(poj 3182)
    Iahub and Permutations(codeforces 314c)
    多边形之战(bzoj 2927)
  • 原文地址:https://www.cnblogs.com/ysw-go/p/5270272.html
Copyright © 2020-2023  润新知