201871010113-刘兴瑞《面向对象程序设计(java)》第十一周学习总结

项目

内容

这个作业属于哪个课程

<任课教师博客主页链接> https://www.cnblogs.com/nwnu-daizh/

这个作业的要求在哪里

<作业链接地址>https://www.cnblogs.com/nwnu-daizh/p/11815810.html

作业学习目标

  1. 理解泛型概念;
  2. 掌握泛型类的定义与使用;
  3. 掌握泛型方法的声明与使用;
  4. 掌握泛型接口的定义与实现;
  5. 了解泛型程序设计,理解其用途。

 

第一部分:理论知识总结:

1.什么是泛型程序设计

  • JDK5.0中增加的泛型类型,是java语言中类型安全的一次重要改进。
  • 泛型:也称参数化类型,就是在定义类,接口和方法时,通过类型参数指示将要处理的对象类型。
  • 泛型程序设计:编写代码可以被很多不同类型的对象所重用

2.泛型类的定义

  • 一个泛型类就是一个或多个类型变量的类,即创建用类型作为参数的类。
  • 泛型类定义格式:class Generics<K,V>(K和V是类的可变类型参数)
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;} 

代码分析:

  1. 代码中Pair类引入类型变量T,用尖括号( <> )括起来,并放在类名的后面。
  2. 泛型类可以有多个类型变量
public class Pair<T,U> {...}  (其中第一个域和第二个域使用不同类型)

   3. 类的类型变量用于指定方法的返回值类型和局部变量的类型。例如:private T first;

  • 用具体的类型替换类型变量就可以实例化泛型类型
Pair<String>
  • 泛型类可以看作普通类的工厂。

解决了以下几个问题:

1 可读性,从字面上就可以判断集合中的内容类型;
2 类型检查,避免插入非法类型。
3 获取数据时不在需要强制类型转换。

3.泛型方法的定义

  • 泛型方法定义如下:
public static <T> T marshalle(T arg){}
  • 与泛型类一样,<T> 是类型参数定义。如:
class ArrayAlg {
public static <T> T getMiddle(T... a){ return a[a.length/2]; } }
  • 调用方式:
String middle=ArrayAlg.<String>getMiddle("John","Q","Public");

4.泛型接口的定义

  • 定义:
public interface IPool <T>
{
     T get();
     int add(T t);
}

5.泛型类型的限定

  • 上界:
  1. 定义泛型变量的上界
public class NumberGeneric< T extends Number>

   2.泛型变量上界说明:

  • extends关键字所声明的上界既可以是一个类,也可以是一个接口;
  • <T extends Bounding Type>表示T应该是绑定类型的子类型。
  • 限定符可以指定多个类型参数,分隔符是 &,不是逗号,因为在类型参数定义中,逗号已经作为多个类型参数的分隔符了。
<T,S extends Comparable & Serializable>
  • 下界:
  1. 定义泛型变量的下界
List<? superCashCard> cards = new ArrayList<T>();

6.通配符类型及使用方法

通配符:

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

通配符的类型限定 

  • Pair<? extends Employee>

  •  Pair<? super Manager>

  • 无限定通配符:Pair<?>

第二部分:实验部分

1、实验目的与要求

(1) 理解泛型概念;

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

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

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

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

2、实验内容和步骤

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

测试程序1:

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

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

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

代码如下:

PairTest1.java:

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);//words是通过类名调用,依赖于ArrayAlg类
      System.out.println("min = " + mm.getFirst());
      System.out.println("max = " + mm.getSecond());
   }
}

class ArrayAlg
{
 /**
         * 获取字符串数组的最小值和最大值。.
         * @param a an array of strings
         * @return 一个具有最小值和最大值的对,如果A为空或空,则为null
     */
   public static Pair<String> minmax(String[] a)//Pair<String>实例化泛型类型
   {
      if (a == null || a.length == 0) return null; // 空指针引用,初始化一个空数组
      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);//返回新的泛型类
   }
}

Pair.java: 

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; }
}

运行结果如图:

测试程序2:

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

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

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

PairTest2.java:

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
{
	/**
          获取T类型对象数组的最小值和最大值。
@param  T类型的对象数组
@return 一个具有最小值和最大值的对,如果A为空或空,则为null
*/
   public static <T extends Comparable> Pair<T> minmax(T[] a) //泛型方法minmax
   {
      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);//返回泛型类
   }
}

运行结果如图:

总结:测试程序二在测试程序一的基础上添加了限定,如果限制只有特定某些类可以传入T参数,那么可以对T进行限定,如:只有实现了特定接口的类:<T extends Comparable>,表示的是Comparable及其子类型。

泛型限定的优点:限制某些类型的子类型可以传入,在一定程度上保证类型安全。

测试程序3:

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

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

PairTest3.java:

package pair3;

/**
 * @version 1.01 2012-01-26
 * @author Cay Horstmann
 */
public class PairTest3
{
   public static void main(String[] args)
   {
      var ceo = new Manager("Gus Greedy", 800000, 2003, 12, 15);
      var cfo = new Manager("Sid Sneaky", 600000, 2003, 12, 15);
      var buddies = new Pair<Manager>(ceo, cfo);      
      printBuddies(buddies);

      ceo.setBonus(1000000);
      cfo.setBonus(500000);
      Manager[] managers = { ceo, cfo };

      var result = new Pair<Employee>();
      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); //SavaHelp捕获通配符类型
   }
// 无法写入公共静态<T超级管理器> ...
}

class PairAlg
{
	//测试一个pair是否包含一个null引用,它不需要实际类型
   public static boolean hasNulls(Pair<?> p)
   {
      return p.getFirst() == null || p.getSecond() == null;
   }

   //交换成对元素
   public static void swap(Pair<?> p) { swapHelper(p); }//由swap调用swapHelper

   //辅助方法
   public static <T> void swapHelper(Pair<T> p)//swapHelper是泛型方法,swap不是
   {
      T t = p.getFirst();
      p.setFirst(p.getSecond());
      p.setSecond(t);
   }
}

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;
   }
}

运行结果如图:

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

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

push(item);            //如item为null,则不入栈直接返回null。
pop();                 //出栈,如为栈为空,则返回null。
peek();                //获得栈顶元素,如为空,则返回null.
public boolean empty();//如为空返回true
public int size();     //返回栈中元素数量

2定义GeneralStackArrayListGeneralStack要求:

  •  类内使用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程序直接退出。否则,输入整数mnm代表入栈个数,n代表出栈个数。然后声明栈变量stack
  • 输入Integer,打印Integer Test。建立可以存放Integer类型的ArrayListGeneralStack。入栈m次,出栈n次。打印栈的toString方法。最后将栈中剩余元素出栈并累加输出。
  • 输入Double ,打印Double Test。剩下的与输入Integer一样。
  • 输入Car,打印Car Test。其他操作与IntegerDouble基本一样。只不过最后将栈中元素出栈,并将其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>{            //泛型类接口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();              //返回栈中元素数量
}
class ArrayListGeneralStack implements GeneralStack{      //创建一个实现GeneralStack接口的类
    ArrayList l =new ArrayList();
    @Override    //重写toString方法
    public String toString() {
        return  l.toString();
    }
  
    @Override      //重写压栈方法
    public Object push(Object item) {
        if (l.add(item)){
            return item;
        }else {
            return false;
        }
    }
  
    @Override     //重写出栈方法
    public Object pop() {
        if (l.size()==0){       //判断栈为空时,返回null
            return null;
        }
        return l.remove(l.size()-1);     
    }
  
    @Override          //重写获取栈顶元素的函数
    public Object peek() {
        return l.get(l.size()-1);
    }
  
    @Override
    public boolean empty() {     //栈为空时,直接返回boolean值
        if (l.size()==0){
            return true;
        }else {
            return false;
        }
    }
  
    @Override       //重写得到栈中元素个数的函数
    public int size() {
        return l.size();
    }
}
 
class Car{              //定义一个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 in =new Scanner(System.in);
        while (true){
            String v = in .nextLine();
            //输入选项,有quit, Integer, Double, Car 4个选项。
            if (v.equals("Double")){    //输入Double ,打印Double Test。            
                System.out.println("Double Test");
                int count=in.nextInt();
                int pop_time=in.nextInt();
                ArrayListGeneralStack arrayListGeneralStack = new ArrayListGeneralStack();//建立可以存放Double类型的ArrayListGeneralStack。
                for (int i=0;i<count;i++){       //入栈次数
                    System.out.println("push:"+arrayListGeneralStack.push(in.nextDouble()));
                }
                for (int i=0;i<pop_time;i++){        //出栈次数
                    System.out.println("pop:"+arrayListGeneralStack.pop());
                }
                System.out.println(arrayListGeneralStack.toString());  //打印栈的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 (v.equals("Integer")){                 //输入Integer,打印Integer Test。
                System.out.println("Integer Test");
                int count=in.nextInt();
                int pop_time=in.nextInt();
                ArrayListGeneralStack arrayListGeneralStack = new ArrayListGeneralStack();//建立可以存放Integer类型的ArrayListGeneralStack。
                for (int i=0;i<count;i++){        //入栈次数
                    System.out.println("push:"+arrayListGeneralStack.push(in.nextInt()));
                }
                for (int i=0;i<pop_time;i++){        //出栈次数
                    System.out.println("pop:"+arrayListGeneralStack.pop());
                }
                System.out.println(arrayListGeneralStack.toString());       //打印栈的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 (v.equals("Car")){     //输入Car,打印Car Test。
                System.out.println("Car Test");
                int count=in.nextInt();
                int pop_time=in.nextInt();
                ArrayListGeneralStack arrayListGeneralStack = new ArrayListGeneralStack();   //创建可以存放Car类型的ArrayListGeneralStack。
                for (int i=0;i<count;i++){   //入栈次数
                    int id=in.nextInt();
                    String name=in.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());       //定义toString方法
                if (arrayListGeneralStack.size()>0){         //栈不为空
                    int size=arrayListGeneralStack.size();
                    for (int i=0;i<size;i++){
                        Car car=(Car) arrayListGeneralStack.pop();//将栈中元素出栈,并将其name依次输出。
                        System.out.println(car.getName());
                    }
                }
                System.out.println("interface GeneralStack");
            }else if (v.equals("quit")){    //如果输入quit,程序直接退出。
                break;
            }
        }
    in.close();
    }
    
}

 运行结果如图:

实验总结:

在这周学习中,我和同学结对编程,互相学习,在这章的学习中,我结合网上的博客,翁恺老师的课程,加深了对这章内容的理解。泛型简单易用,类型安全 泛型的主要目标是实现java的类型安全。 泛型可以使编译器知道一个对象的限定类型是什么,这样编译器就可以在一个高的程度上验证这个类型。消除了强制类型转换 使得代码可读性好,减少了很多出错的机会。泛型的好处是安全简单。泛型的好处是在编译的时候检查类型安全,并且所有的强制转换都是自动和隐式的,提高代码的重用率。

猜你喜欢

转载自www.cnblogs.com/lxr0/p/11818894.html