zoukankan      html  css  js  c++  java
  • 201871010101陈来弟《面向对象程序设计(Java)》第十一周学习总结 201871010101

            201871010101-陈来弟《面向对象程序设计(Java)》第十一周学习总结

    实验九  泛型程序设计技术

    实验时间 2019-11-8

    第一部分:理论基础知识

    1.什么是泛型类

        泛型是具有占位符(类型参数)的类、结构、接口和方法,这些占位符是类、结构、接口和方法所存储或使用的一个或多个类型的占位符。泛型集合类可以将类型参数用作它所存储的对象的类型的占位符;类型参数作为其字段的类型和其方法的参数类型出现。泛型方法可以将其类型参数用作其返回值的类型或者其形参的类型之一。下面的代码阐释一个简单的泛型类定义。在创建泛型类的实例时,会指定实际类型来替换类型参数。这会建立一个新的泛型类,称为构造泛型类,选定的类型将替换所有出现的类型参数。最后得到按照您选择的类型定制的类型安全的类。     

       “泛型类型定义”是用作模板的类、结构或接口声明,其中具有该类、结构或接口声明可以包含或使用的类型的占位符。例如,Dictionary 类可以包含两种类型:键和值。因为它只是一个模板,您不能创建作为泛型类型定义的类、结构或接口的实例。

      “泛型类型参数”或称“类型参数”是泛型类型或方法定义中的占位符。Dictionary 泛型类型具有两个类型参数:TKey 和 TValue,分别表示其键和值的类型。

      “构造泛型类型”或称“构造类型”是为泛型类型定义的泛型类型参数指定类型得到的结果。

      “泛型类型参数”是替换泛型类型参数的任何类型。

        一般术语“泛型类型”包括构造类型和泛型类型定义。

      “约束”是加在泛型类型参数上的限制。例如,可以将类型参数限制为实现 IComparer 泛型接口的类型以确保可以对该类型的实例进行排序。还可以将类型参数限制为具有特定基类的类型、具有默认构造函数的类型或是引用类型或值类型。泛型类型的用户不能替换不满足这些约束的类型参数。

    2.“泛型方法定义”是具有两个参数列表的方法:一个泛型类型参数列表和一个形参列表。类型参数可以作为返回类型或形参的类型出现。泛型方法可以出现在泛型或非泛型类型上。需要注意的是,并不是只要方法属于泛型类型,或者甚至是方法的形参的类型是封闭类型的泛型参数,就可以说方法是泛型方法。只有当方法具有它自己的类型参数列表时,才能称其为泛型方法。

    3.泛型接口的定义

     (1)定义 public interface IPool { T get(); int add(T t); }

     

     (2)实现

     

            public class GenericPool implements IPool { … }

     

            public class GenericPool implements IPool

     

            { … }

     

    4.泛型变量的限定

     (1) 定义泛型变量的上界 public class NumberGeneric< T extends Number>

     (2) 泛型变量上界的说明  上述声明规定了NumberGeneric类所能处理的泛型变量类型需和Number有继承关系;  extends关键字所声明的上界既可以是一个类,也可以是一个接口;

     (3)< T extends  BoundingType> 表示T应该是绑定类型的子类型。  一个类型变量或通配符可以有多个限定,限定类型用“&”分割。例如:< T extends Comparable & Serializable >

     (4) 定义泛型变量的下界 List cards = new ArrayList(); (5) 泛型变量下界的说明– 通过使用super关键字可以固定泛型参数的类型为某种类型或者其超类 – 当程序希望为一个方法的参数限定类型时,通常可以使用下限通配符

     

         public static void sort(T[] a,Comparator c) { … }

     

    5.通配符类型

            通配符 – “?”符号表明参数的类型可以是任何一种类型,它和参数T的含义是有区别的。T表示一种未知类型,而“?”表示任何一种类型。这种通配符一般有以下三种用法:     – 单独的?,用于表示任何类型。    – ? extends type,表示带有上界。    – ? super type,表示带有下界。

     第二部分:实验部分

    1、实验目的与要求

    (1) 理解泛型概念;

    (2) 掌握泛型类的定义与使用;

    (3) 了解泛型方法的声明与使用;

    (4) 掌握泛型接口的定义与实现;

    (5) 理解泛型程序设计,理解其用途。

    2、实验内容和步骤

    实验1 导入第8章示例程序,测试程序并进行代码注释。

    测试程序1:

    编辑、调试、运行教材311312页代码,结合程序运行结果理解程序;

    在泛型类定义及使用代码处添加注释;

    掌握泛型类的定义及使用。 

    插入代码如下:

     

    package pair1;
    
    /**
     * @version 1.00 2004-05-10
     * @author Cay Horstmann
     */
    //泛型类使得类具有通用性
    public class Pair<T> //引入类型变量T
    {
       private T first;
       private T second;
    
       public Pair() { first = null; second = null; }
       public Pair(T first, T second) { this.first = first;  this.second = second; }
    
       public T getFirst() { return first; }
       public T getSecond() { return second; }
    
       public void setFirst(T newValue) { first = newValue; }
       public void setSecond(T newValue) { second = newValue; }
    }

     

    package pair1;
    
    /**
     * @version 1.01 2012-01-26
     * @author Cay Horstmann
     */
    public class PairTest1
    {
       public static void main(String[] args)
       {
          String[] words = { "Mary", "had", "a", "little", "lamb" };
          Pair<String> mm = ArrayAlg.minmax(words);//泛型类对象String Pair类,静态方法用类名调用方法,泛型字符串类型,按字典序排序
          System.out.println("min = " + mm.getFirst());
          System.out.println("max = " + mm.getSecond());
       }
    }
    
    class ArrayAlg
    {
       /**
        * Gets the minimum and maximum of an array of strings.
        * @param a an array of strings
        * @return a pair with the min and max values, or null if a is null or empty
        */
       public static Pair<String> minmax(String[] a)//普通方法,返回值是一个实例化的Pair类对象
       {
          if (a == null || a.length == 0) return null;//length是数组的属性值
          String min = a[0];
          String max = a[0];
          for (int i = 1; i < a.length; i++)
          {
             if (min.compareTo(a[i]) > 0) min = a[i];
             if (max.compareTo(a[i]) < 0) max = a[i];
          }
          return new Pair<>(min, max);//用泛型类来返回两个值
       }
    }

    运行结果如下:

     

    测试程序2:

    编辑、调试运行教材315 PairTest2,结合程序运行结果理解程序;

    在泛型程序设计代码处添加相关注释;

    了解泛型方法、泛型变量限定的定义及用途。

     代码如下:

    package pair2;
    
    /**
     * @version 1.00 2004-05-10
     * @author Cay Horstmann
     */
    public class Pair<T> 
    {
       private T first;
       private T second;
    
       public Pair() { first = null; second = null; }
       public Pair(T first, T second) { this.first = first;  this.second = second; }
    
       public T getFirst() { return first; }
       public T getSecond() { return second; }
    
       public void setFirst(T newValue) { first = newValue; }
       public void setSecond(T newValue) { second = newValue; }
    }
    package pair2;
    
    import java.time.*;
    
    /**
     * @version 1.02 2015-06-21
     * @author Cay Horstmann
     */
    public class PairTest2
    {
       public static void main(String[] args)
       {
          LocalDate[] birthdays = 
             { 
                LocalDate.of(1906, 12, 9), // G. Hopper
                LocalDate.of(1815, 12, 10), // A. Lovelace
                LocalDate.of(1903, 12, 3), // J. von Neumann
                LocalDate.of(1910, 6, 22), // K. Zuse
             };
          Pair<LocalDate> mm = ArrayAlg.minmax(birthdays);
          System.out.println("min = " + mm.getFirst());
          System.out.println("max = " + mm.getSecond());
       }
    }
    
    class ArrayAlg
    {
       /**
          Gets the minimum and maximum of an array of objects of type T.
          @param a an array of objects of type T
          @return a pair with the min and max values, or null if a is null or empty
       */
       public static <T extends Comparable> Pair<T> minmax(T[] a) //泛型方法,有上界约束
       {
          if (a == null || a.length == 0) return null;
          T min = a[0];
          T max = a[0];
          for (int i = 1; i < a.length; i++)
          {
             if (min.compareTo(a[i]) > 0) min = a[i];
             if (max.compareTo(a[i]) < 0) max = a[i];
          }
          return new Pair<>(min, max);
       }
    }

     运行结果如下:

     

     

    测试程序3:

    用调试运行教材335 PairTest3,结合程序运行结果理解程序;

    了解通配符类型的定义及用途。

     

    Employee.java 
    
    package pair3;
    
    import java.time.*;
    
    public class Employee
    {  
       private String name;
       private double salary;
       private LocalDate hireDay;
    
       public Employee(String name, double salary, int year, int month, int day)
       {
          this.name = name;
          this.salary = salary;
          hireDay = LocalDate.of(year, month, day);
       }
    
       public String getName()
       {
          return name;
       }
    
       public double getSalary()
       {  
          return salary;
       }
    
       public LocalDate getHireDay()
       {  
          return hireDay;
       }
    
       public void raiseSalary(double byPercent)
       {  
          double raise = salary * byPercent / 100;
          salary += raise;
       }
    }

     

    Manager.java 
    
    package pair3;
    
    public class Manager extends Employee
    {  
       private double bonus;
    
       /**
          @param name the employee's name
          @param salary the salary
          @param year the hire year
          @param month the hire month
          @param day the hire day
       */
       public Manager(String name, double salary, int year, int month, int day)
       {  
          super(name, salary, year, month, day);
          bonus = 0;
       }
    
       public double getSalary()
       { 
          double baseSalary = super.getSalary();
          return baseSalary + bonus;
       }
    
       public void setBonus(double b)
       {  
          bonus = b;
       }
    
       public double getBonus()
       {  
          return bonus;
       }
    }

     

    Pair.java 
    
    
    package pair3;
    
    /**
     * @version 1.00 2004-05-10
     * @author Cay Horstmann
     */
    public class Pair<T> 
    {
       private T first;
       private T second;
    
       public Pair() { first = null; second = null; }
       public Pair(T first, T second) { this.first = first;  this.second = second; }
    
       public T getFirst() { return first; }
       public T getSecond() { return second; }
    
       public void setFirst(T newValue) { first = newValue; }
       public void setSecond(T newValue) { second = newValue; }
    }
    PairTest3.java
    
    package pair3;
    
    /**
     * @version 1.01 2012-01-26
     * @author Cay Horstmann
     */
    public class PairTest3
    {
       public static void main(String[] args)
       {
          Manager ceo = new Manager("Gus Greedy", 800000, 2003, 12, 15);
          Manager cfo = new Manager("Sid Sneaky", 600000, 2003, 12, 15);
          Pair<Manager> buddies = new Pair<Manager>(ceo, cfo); //类型变量        
          printBuddies(buddies);
    
          ceo.setBonus(1000000);
          cfo.setBonus(500000);
          Manager[] managers = { ceo, cfo };
    
          Pair<Employee> result = new Pair<Employee>();//也可以用Manager
          minmaxBonus(managers, result);
          System.out.println("first: " + result.getFirst().getName() 
             + ", second: " + result.getSecond().getName());
          maxminBonus(managers, result);
          System.out.println("first: " + result.getFirst().getName() 
             + ", second: " + result.getSecond().getName());
       }
    
       public static void printBuddies(Pair<? extends Employee> p)//上界约束
       {
          Employee first = p.getFirst();
          Employee second = p.getSecond();
          System.out.println(first.getName() + " and " + second.getName() + " are buddies.");
       }
    
       public static void minmaxBonus(Manager[] a, Pair<? super Manager> result)//采用通配符来定义第二个类型变量
       {
          if (a.length == 0) return;
          Manager min = a[0];
          Manager max = a[0];
          for (int i = 1; i < a.length; i++)
          {
             if (min.getBonus() > a[i].getBonus()) min = a[i];
             if (max.getBonus() < a[i].getBonus()) max = a[i];
          }
          result.setFirst(min);
          result.setSecond(max);
       }
    
       public static void maxminBonus(Manager[] a, Pair<? super Manager> result)
       {
          minmaxBonus(a, result);
          PairAlg.swapHelper(result); // OK--swapHelper captures wildcard type
       }
       // can't write public static <T super manager> . . .
    }
    
    class PairAlg
    {
       public static boolean hasNulls(Pair<?> p)//?类型变量的通配符,单独的?表示任何一种类型,T表示一种未知类型
       //将hasNulls转换成泛型方法
       //测试一个pair是否包含一个null引用
       {
          return p.getFirst() == null || p.getSecond() == null;
       }
     //编写一个交换成对元素的方法
       public static void swap(Pair<?> p) { swapHelper(p); }
    
       public static <T> void swapHelper(Pair<T> p)//泛型方法
       {
          T t = p.getFirst();//保存第一个元素
          p.setFirst(p.getSecond());
          p.setSecond(t);
       }
    }

    运行结果如下:

     

    实验2结对编程练习,将程序提交到PTA(2019面向对象程序设计基础知识测试题(2)

    1 编写一个泛型接口GeneralStack,要求类方法对任何引用类型数据都适用。GeneralStack接口中方法如下:

    push(item);            //如item为null,则不入栈直接返回null。

    pop();                 //出栈,如为栈为空,则返回null。

    peek();                //获得栈顶元素,如为空,则返回null.

    public boolean empty();//如为空返回true

    public int size();     //返回栈中元素数量

    2定义GeneralStack的类ArrayListGeneralStack要求:

    ü 类内使用ArrayList对象存储堆栈数据,名为list;

    ü 方法: public String toString()//代码为return list.toString();

    ü 代码中不要出现类型不安全的强制转换。

    3定义Car类,类的属性有:

    private int id;

    private String name;

    方法:Eclipse自动生成setter/getter,toString方法。

    4main方法要求

    ü 输入选项,有quit, Integer, Double, Car 4个选项。如果输入quit,程序直接退出。否则,输入整数m与n。m代表入栈个数,n代表出栈个数。然后声明栈变量stack。

    ü 输入Integer,打印Integer Test。建立可以存放Integer类型的ArrayListGeneralStack。入栈m次,出栈n次。打印栈的toString方法。最后将栈中剩余元素出栈并累加输出。

    ü 输入Double ,打印Double Test。剩下的与输入Integer一样。

    ü 输入Car,打印Car Test。其他操作与Integer、Double基本一样。只不过最后将栈中元素出栈,并将其name依次输出。

    特别注意:如果栈为空,继续出栈,返回null

    输入样例

    Integer

    5

    2

    1 2 3 4 5

    Double

    5

    3

    1.1 2.0 4.9 5.7 7.2

    Car

    3

    2

    1 Ford

    2 Cherry

    3 BYD

    quit

    输出样例

    Integer Test

    push:1

    push:2

    push:3

    push:4

    push:5

    pop:5

    pop:4

    [1, 2, 3]

    sum=6

    interface GeneralStack

    Double Test

    push:1.1

    push:2.0

    push:4.9

    push:5.7

    push:7.2

    pop:7.2

    pop:5.7

    pop:4.9

    [1.1, 2.0]

    sum=3.1

    interface GeneralStack

    Car Test

    push:Car [id=1, name=Ford]

    push:Car [id=2, name=Cherry]

    push:Car [id=3, name=BYD]

    pop:Car [id=3, name=BYD]

    pop:Car [id=2, name=Cherry]

    [Car [id=1, name=Ford]]

    Ford

    interface GeneralStack

    代码如下:

    
    

    import java.util.ArrayList;
    import java.util.Scanner;

    interface GeneralStack<T>{
    public T push(T item); //如item为null,则不入栈直接返回null。
    public T pop(); //出栈,如为栈为空,则返回null。
    public T peek(); //获得栈顶元素,如为空,则返回null.
    public boolean empty();//如为空返回true
    public int size(); //返回栈中元素数量
    }
    //定义GeneralStack的子类ArrayListGeneralStack
    class ArrayListGeneralStack implements GeneralStack{
    ArrayList list=new ArrayList();
    @Override
    public String toString() {
    return list.toString();
    }

    @Override
    public Object pop() {
    if (list.size()==0){
    return null;
    }
    return list.remove(list.size()-1);
    }
    @Override
    public Object push(Object item) {
    if (list.add(item)){
    return item;
    }else {
    return false;
    }
    }
    @Override
    public Object peek() {
    return list.get(list.size()-1);
    }

    @Override
    public boolean empty() {
    if (list.size()==0){
    return true;
    }else {
    return false;
    }
    }

    @Override
    public int size() {
    return list.size();
    }
    }
    //定义Car类
    class Car{
    private int id;
    private String name;

    @Override
    public String toString() {
    return "Car [" +
    "id=" + id +
    ", name=" + name +
    ']';
    }

    public int getId() {
    return id;
    }

    public void setId(int id) {
    this.id = id;
    }

    public String getName() {
    return name;
    }

    public void setName(String name) {
    this.name = name;
    }

    public Car(int id, String name) {
    this.id = id;
    this.name = name;
    }
    }
    public class Main {
    public static void main(String[] args) {
    Scanner sc=new Scanner(System.in);
    while (true){
    String s=sc.nextLine();
    if (s.equals("Double")){
    System.out.println("Double Test");
    int count=sc.nextInt();
    int pop_time=sc.nextInt();
    ArrayListGeneralStack arrayListGeneralStack = new ArrayListGeneralStack();//建立可以存放Double类型的ArrayListGeneralStack
    for (int i=0;i<count;i++){
    System.out.println("push:"+arrayListGeneralStack.push(sc.nextDouble()));
    }
    for (int i=0;i<pop_time;i++){
    System.out.println("pop:"+arrayListGeneralStack.pop());
    }
    System.out.println(arrayListGeneralStack.toString());
    double sum=0;
    int size=arrayListGeneralStack.size();
    for (int i=0;i<size;i++){
    sum+=(double)arrayListGeneralStack.pop();
    }
    System.out.println("sum="+sum);
    System.out.println("interface GeneralStack");
    }
    else if (s.equals("Integer")){
    System.out.println("Integer Test");
    int count=sc.nextInt();
    int pop_time=sc.nextInt();
    ArrayListGeneralStack arrayListGeneralStack = new ArrayListGeneralStack();//建立可以存放Integer类型的ArrayListGeneralStack
    for (int i=0;i<count;i++){
    System.out.println("push:"+arrayListGeneralStack.push(sc.nextInt()));
    }
    for (int i=0;i<pop_time;i++){
    System.out.println("pop:"+arrayListGeneralStack.pop());
    }
    System.out.println(arrayListGeneralStack.toString());
    int sum=0;
    int size=arrayListGeneralStack.size();
    for (int i=0;i<size;i++){
    sum+=(int)arrayListGeneralStack.pop();
    }
    System.out.println("sum="+sum);
    System.out.println("interface GeneralStack");
    }
    else if (s.equals("Car")){
    System.out.println("Car Test");
    int count=sc.nextInt();
    int pop_time=sc.nextInt();
    ArrayListGeneralStack arrayListGeneralStack = new ArrayListGeneralStack();//创建可以存放Car类型的ArrayListGeneralStack
    for (int i=0;i<count;i++){
    int id=sc.nextInt();
    String name=sc.next();
    Car car = new Car(id,name);
    System.out.println("push:"+arrayListGeneralStack.push(car));
    }
    for (int i=0;i<pop_time;i++){
    System.out.println("pop:"+arrayListGeneralStack.pop());
    }
    System.out.println(arrayListGeneralStack.toString());
    if (arrayListGeneralStack.size()>0){
    int size=arrayListGeneralStack.size();
    for (int i=0;i<size;i++){
    Car car=(Car) arrayListGeneralStack.pop();
    System.out.println(car.getName());
    }
    }
    System.out.println("interface GeneralStack");
    }
    else if (s.equals("quit")){
    break;
    }
    }

    }
    }

     

    运行结果如下:

     第三部分:实验总结

         通过这周的学习,我了解了泛型设计技术的概念,泛型程序设计意味着编写代码可以被很多不同类型的对象所重用,以及它的好处和限制,基本上会运用泛型技术设计程序,但是在很多知识的运用方面仍然不太懂,在之后的学习中要更加努力,课后要多练习,尤其是关于本章节的泛型的使用等各个方面,也希望老师能更加详细的讲解。

     

  • 相关阅读:
    vmware安装ubuntu
    加快pip install的速度
    在Dataframe中寻找特定值所在行的行号
    后续:尝试交易策略
    小实验:股票涨幅日间的相关性
    大数据之数据预处理
    并查集
    2020华为杯数学建模B题-RON建模 赛后总结与分析
    二叉树的遍历总结
    几数之和分析,解法,优化和总结
  • 原文地址:https://www.cnblogs.com/wing2438/p/11836564.html
Copyright © 2011-2022 走看看