Java学习者论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

手机号码,快捷登录

恭喜Java学习者论坛(https://www.javaxxz.com)已经为数万Java学习者服务超过8年了!积累会员资料超过10000G+
成为本站VIP会员,下载本站10000G+会员资源,购买链接:点击进入购买VIP会员
JAVA高级面试进阶视频教程Java架构师系统进阶VIP课程

分布式高可用全栈开发微服务教程

Go语言视频零基础入门到精通

Java架构师3期(课件+源码)

Java开发全终端实战租房项目视频教程

SpringBoot2.X入门到高级使用教程

大数据培训第六期全套视频教程

深度学习(CNN RNN GAN)算法原理

Java亿级流量电商系统视频教程

互联网架构师视频教程

年薪50万Spark2.0从入门到精通

年薪50万!人工智能学习路线教程

年薪50万!大数据从入门到精通学习路线年薪50万!机器学习入门到精通视频教程
仿小米商城类app和小程序视频教程深度学习数据分析基础到实战最新黑马javaEE2.1就业课程从 0到JVM实战高手教程 MySQL入门到精通教程
查看: 246|回复: 0

[泛型学习]范型入门实例

[复制链接]
  • TA的每日心情
    开心
    2021-3-12 23:18
  • 签到天数: 2 天

    [LV.1]初来乍到

    发表于 2014-10-30 23:56:42 | 显示全部楼层 |阅读模式
    一、定义范型类
    1. /**
    2.    @author Cay Horstmann
    3. */
    4. public class Pair< T> //范型类,T是类型参数,T只能是类类型
    5. {
    6.    public Pair() { first = null; second = null; }
    7.    public Pair(T first, T second) {
    8.      this.first = first;  this.second = second;
    9.    }
    10.    public T getFirst() { return first; }
    11.    public T getSecond() { return second; }
    12.    public void setFirst(T newValue) { first = newValue; }
    13.    public void setSecond(T newValue) { second = newValue; }
    14.    private T first;
    15.    private T second;
    16. }
    复制代码

      
      
      二、测试一
    1. public class PairTest1
    2. {
    3.    public static void main(String[] args)
    4.    {
    5.       String[] words = { "Mary", "had", "a", "little", "lamb" };
    6.       Pair< String> mm = ArrayAlg.minmax(words);//字符串版本的范型
    7.       System.out.println("min = " + mm.getFirst());
    8.       System.out.println("max = " + mm.getSecond());
    9.    }
    10. }

    11. class ArrayAlg
    12. {
    13.    /**
    14.       Gets the minimum and maximum of an array of strings.
    15.       @param a an array of strings
    16.       @return a pair with the min and max value, or null if a is
    17.       null or empty
    18.    */
    19.    public static Pair< String> minmax(String[] a)
    20.    {
    21.       if (a == null || a.length == 0) return null;
    22.       String min = a[0];
    23.       String max = a[0];
    24.       for (int i = 1; i < a.length; i++)
    25.       {
    26.          if (min.compareTo(a[i]) > 0) min = a[i];
    27.          if (max.compareTo(a[i]) < 0) max = a[i];
    28.       }
    29.       return new Pair< String>(min, max);
    30.    }
    31. }
    32. 结果:
    33. C:java>java   PairTest1
    34. min = Mary
    35. max = little

    36. 三、测试二
    37. import java.util.*;
    38. public class PairTest2
    39. {
    40.    public static void main(String[] args)
    41.    {
    42.       GregorianCalendar[] birthdays =
    43.          {
    44.             new GregorianCalendar(1906, Calendar.DECEMBER, 9), // G. Hopper
    45.             new GregorianCalendar(1815, Calendar.DECEMBER, 10), // A. Lovelace
    46.             new GregorianCalendar(1903, Calendar.DECEMBER, 3), // J. von Neumann
    47.             new GregorianCalendar(1910, Calendar.JUNE, 22), // K. Zuse
    48.          };
    49.       Pair< GregorianCalendar> mm = ArrayAlg.minmax(birthdays);//日期版的范型
    50.       System.out.println("min = " + mm.getFirst().getTime());
    51.       System.out.println("max = " + mm.getSecond().getTime());
    52.    }
    53. }

    54. class ArrayAlg
    55. {
    56.    /**
    57.       Gets the minimum and maximum of an array of objects of type T.
    58.       @param a an array of objects of type T
    59.       @return a pair with the min and max value, or null if a is
    60.       null or empty
    61.    */
    62.    public static < T extends Comparable> Pair< T> minmax(T[] a) //范型方法,注意类型参数在方法的返回类型之前声明。
    63.    {
    64.       if (a == null || a.length == 0) return null;
    65.       T min = a[0];
    66.       T max = a[0];
    67.       for (int i = 1; i < a.length; i++)
    68.       {
    69.          if (min.compareTo(a[i]) > 0) min = a[i];
    70.          if (max.compareTo(a[i]) < 0) max = a[i];
    71.       }
    72.       return new Pair< T>(min, max);
    73.    }
    74. }
    75. 运行结果:
    76. C:java>java   PairTest2
    77. min = Sun Dec 10 00:00:00 CST 1815
    78. max = Wed Jun 22 00:00:00 CST 1910

    79. 四、测试三
    80. import java.util.*;
    81. public class PairTest3
    82. {
    83.    public static void main(String[] args)
    84.    {
    85.       Manager ceo = new Manager("Gus Greedy", 800000, 2003, 12, 15);
    86.       Manager cfo = new Manager("Sid Sneaky", 600000, 2003, 12, 15);
    87.       Pair< Manager> buddies = new Pair< Manager>(ceo, cfo);//管理人员版的范型      
    88.       printBuddies(buddies);
    89.       ceo.setBonus(1000000);
    90.       cfo.setBonus(500000);
    91.       Manager[] managers = { ceo, cfo };
    92.       Pair< Employee> result = new Pair< Employee>();//雇员版的范型
    93.       minMaxBonus(managers, result);
    94.       System.out.println("first: " + result.getFirst().getName()
    95.          + ", second: " + result.getSecond().getName());
    96.       maxMinBonus(managers, result);
    97.       System.out.println("first: " + result.getFirst().getName()
    98.          + ", second: " + result.getSecond().getName());
    99.    }

    100.    public static void printBuddies(Pair< ? extends Employee> p)//指定上界,只有Employee或其子类才是可接受的参数
    101.    {
    102.       Employee first = p.getFirst();
    103.       Employee second = p.getSecond();
    104.       System.out.println(first.getName() + " and " + second.getName() + " are buddies.");
    105.    }

    106. public static void minMaxBonus(Manager[] a,Pair< ? super Manager> result)//指定下界,只有Manager的超类才是可接受的参数
    107.    {
    108.       if (a == null || a.length == 0) return;
    109.       Manager min = a[0];
    110.       Manager max = a[0];
    111.       for (int i = 1; i < a.length; i++)
    112.       {
    113.          if (min.getBonus() > a[i].getBonus()) min = a[i];
    114.          if (max.getBonus() < a[i].getBonus()) max = a[i];
    115.       }
    116.       result.setFirst(min);
    117.       result.setSecond(max);
    118.    }

    119.    public static void maxMinBonus(Manager[] a, Pair< ? super Manager> result)//指定了下界
    120.    {
    121.       minMaxBonus(a, result);
    122.       PairAlg.swapHelper(result); // OK--swapHelper captures wildcard type
    123.    }
    124. }

    125. class PairAlg
    126. {
    127.    public static boolean hasNulls(Pair< ?> p)//通配符参数"?"表示未知类型,Pair< ?>可以匹配任一Pair对象
    128.    {
    129.       return p.getFirst() == null || p.getSecond() == null;
    130.    }
    131.    public static void swap(Pair< ?> p) { swapHelper(p); }
    132.    public static < T> void swapHelper(Pair< T> p)
    133.    {
    134.       T t = p.getFirst();
    135.       p.setFirst(p.getSecond());
    136.       p.setSecond(t);
    137.    }
    138. }

    139. //雇员类
    140. class Employee
    141. {  
    142.    public Employee(String n, double s, int year, int month, int day)
    143.    {  
    144.       name = n;//姓名
    145.       salary = s;//薪水
    146.       GregorianCalendar calendar = new GregorianCalendar(year, month - 1, day);
    147.       hireDay = calendar.getTime();//受雇的日期
    148.    }
    149.    public String getName()
    150.    {
    151.       return name;
    152.    }
    153.    public double getSalary()
    154.    {  
    155.       return salary;
    156.    }
    157.    public Date getHireDay()
    158.    {  
    159.       return hireDay;
    160.    }
    161.    public void raiseSalary(double byPercent)
    162.    {  
    163.       double raise = salary * byPercent / 100;
    164.       salary += raise;
    165.    }
    166.    private String name;
    167.    private double salary;
    168.    private Date hireDay;
    169. }

    170. //管理人员类
    171. class Manager extends Employee
    172. {  
    173.    /**
    174.       @param n the employee"s name
    175.       @param s the salary
    176.       @param year the hire year
    177.       @param month the hire month
    178.       @param day the hire day
    179.    */
    180.    public Manager(String n, double s, int year, int month, int day)
    181.    {  
    182.       super(n, s, year, month, day);
    183.       bonus = 0;
    184.    }
    185.    public double getSalary()
    186.    {
    187.       double baseSalary = super.getSalary();
    188.       return baseSalary + bonus;
    189.    }
    190.    public void setBonus(double b)
    191.    {  
    192.       bonus = b;
    193.    }
    194.    public double getBonus()
    195.    {  
    196.       return bonus;
    197.    }
    198.    private double bonus;//奖金
    199. }
    200. 运行结果:
    201. C:java>java   PairTest3
    202. Gus Greedy and Sid Sneaky are buddies.
    203. first: Sid Sneaky, second: Gus Greedy
    204. first: Gus Greedy, second: Sid Sneaky

    205.                      
    复制代码

       
         
         
          
          

            
          

            
          
         
       

    1.                      
    复制代码

      


    源码下载:http://file.javaxxz.com/2014/10/30/235642656.zip
    回复

    使用道具 举报

    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    QQ|手机版|Java学习者论坛 ( 声明:本站资料整理自互联网,用于Java学习者交流学习使用,对资料版权不负任何法律责任,若有侵权请及时联系客服屏蔽删除 )

    GMT+8, 2025-2-25 22:04 , Processed in 0.382062 second(s), 34 queries .

    Powered by Discuz! X3.4

    © 2001-2017 Comsenz Inc.

    快速回复 返回顶部 返回列表