zoukankan      html  css  js  c++  java
  • 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());
      }
     }
    
    }
  • 相关阅读:
    【HDOJ】2267 How Many People Can Survive
    【HDOJ】2268 How To Use The Car
    【HDOJ】2266 How Many Equations Can You Find
    【POJ】2278 DNA Sequence
    【ZOJ】3430 Detect the Virus
    【HDOJ】2896 病毒侵袭
    求奇数的乘积
    平方和与立方和
    求数列的和
    水仙花数
  • 原文地址:https://www.cnblogs.com/ysw-go/p/5270272.html
Copyright © 2011-2022 走看看