狄慧201771010104《面向对象程序设计(java)》第十周学习总结

实验十  泛型程序设计技术

实验时间 2018-11-1

第一部分:理论知识学习部分

(一)、泛型程序设计的定义

1、JDK 5.0 中增加的泛型类型,是Java 语言中类型安全的一次重要改进。

2、 泛型:也称参数化类型(parameterized type),就是在定义类、接口和方法时,通过类型参数指示将要处理的对象类型。(如ArrayList类)

3、泛型程序设计(Generic programming):编写代码可以被很多不同类型的对象所重用。

4、一个泛型类(generic class)就是具有一个或多个类型变量的类,即创建用类型作为参数的类。如一个泛型类定义格式如下:class Generics<K,V>其中的K和V是类中的可变类型参数。

5、Pair类引入了一个类型变量T,用尖括号(<>)括起来,并放在类名的后面。

6、 泛型类可以有多个类型变量。例如:public class Pair<T, U> { … }

7、 类定义中的类型变量用于指定方法的返回类型以及域、局部变量的类型。

扫描二维码关注公众号,回复: 3927968 查看本文章

(二)、泛型方法的声明

1、 泛型方法

(1) 除了泛型类外,还可以只单独定义一个方法作为泛型方法,用于指定方法参数或者返回值为泛型类型,留待方法调用时确定。

(2) 泛型方法可以声明在泛型类中,也可以声明在普通类中。

第二部分:实验

1、实验目的与要求

(1) 理解泛型概念;

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

(3) 掌握泛型方法的声明与使用;

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

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

2、实验内容和步骤

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

测试程序1:

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

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

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

package pair1;

/**
 * @version 1.00 2004-05-10
 * @author Cay Horstmann
 */
public class Pair<T> //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 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" };//ArrayAlg调用静态方法minmax();
      Pair<String> mm = ArrayAlg.minmax(words);
      
      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 value, or null if a is null or empty
    */
   public static Pair<String> minmax(String[] a)//定义静态泛型方法,将类型变量实例化为String;
   {
      if (a == null || a.length == 0) return null;//a.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 PairTest1.Pair;
import java.time.*;

/**
 * @version 1.02 2015-06-21
 * @author Cay Horstmann
 */
public class PairTest2
{
   public static void main(String[] args)
   {
      LocalDate[] birthdays = 
         { //按ASCII码比较,大写字母比小写字母的ASCII码小;
            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
         };
      //ArrayAlg调用静态方法minmax();
      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 value, 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);//返回一个实例化泛型Pair类对象;
   }
}

测试程序3:

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

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

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; }
}
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<>(ceo, cfo);      
      printBuddies(buddies);

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

      Pair<Employee> result = new Pair<>();
      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)
  //<? extends type>表示带有上界 
   
   {
      Employee first = p.getFirst();
      Employee second = p.getSecond();
      System.out.println(first.getName() + " and " + second.getName() + " are buddies.");
   }
 //"?"在这儿是通配符,符号表明参数的类型可以是任何一种类型,它和参数T的含义是有区别的
   public static void minmaxBonus(Manager[] a, Pair<? super Manager> result)//<? super type>表示带有下界
{
      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);
   }//T表示一种未知类型,而“?”表示任何一种类型
   public static void maxminBonus(Manager[] a, Pair<? super Manager> result)
   {
      minmaxBonus(a, result);
      PairAlg.swapHelper(result); // swapHelper捕获通配符类型
   }
}

class PairAlg
{
   public static boolean hasNulls(Pair<?> p)
   {
      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);
   }
}
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;
   }
}
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:编程练习:

编程练习1:实验九编程题总结

l  实验九编程练习1总结(从程序总体结构说明、模块说明,目前程序设计存在的困难与问题三个方面阐述)。

1>程序总体结构:主类Main和子类test;

2>模块说明:主类当中进行文件的读取以及操作,test类实现了comparable接口,控制其输出形式;

3>困难与问题:对捕获知识掌握的不好,对变量名有时不能统一。

l  实验九编程练习2总结(从程序总体结构说明、模块说明,目前程序设计存在的困难与问题三个方面阐述)。

1>程序总体结构:主类和yunsuan类;

2>模块说明:主类调用以及实现yunsuan类的功能,yunsuan类主要模块化实现各种操作;

3>困难与问题:在yunsuan类的编写中,很多操作不知怎样具体化,对于switch语句掌握不好,不符合基础运算的要求。

编程练习2:采用泛型程序设计技术改进实验九编程练习2,使之可处理实数四则运算,其他要求不变。

package fghjg;
import java.util.Random;
import java.util.Scanner;

import java.io.FileNotFoundException;

import java.io.PrintWriter;

public class Main{
    public static void main(String[] args)
    {
        
        yunsuan counter=new yunsuan();//与其它类建立联系
    PrintWriter out=null;
    try {
        out=new PrintWriter("D:/text.txt");//将文件里的内容读入到D盘名叫text的文件中
         
    }catch(FileNotFoundException e) {
        System.out.println("文件找不到");
        e.printStackTrace();
    }
    
    
    int sum=0;

    for(int i=0;i<10;i++)
    {
    int a=new Random().nextInt(100);
    int b=new Random().nextInt(100);
    Scanner in=new Scanner(System.in);
    //in.close();
    
    switch((int)(Math.random()*4))
    
    {
    
    case 0:
        System.out.println( ""+a+"+"+b+"=");
        
        int c1 = in.nextInt();
        out.println(a+"+"+b+"="+c1);
        if (c1 == counter.plus(a, b)) {
            sum += 10;
            System.out.println("答案正确");
        }
        else {
            System.out.println("答案错误");
        }
        
        break ;
    case 1:
        if(a<b)
                        {
                                 int temp=a;
                                 a=b;
                                 b=temp;
                             }//为避免减数比被减数大的情况

         System.out.println(""+a+"-"+b+"=");
         /*while((a-b)<0)
         {  
             b = (int) Math.round(Math.random() * 100);
             
         }*/
        int c2 = in.nextInt();
        
        out.println(a+"-"+b+"="+c2);
        if (c2 == counter.minus(a, b)) {
            sum += 10;
            System.out.println("答案正确");
        }
        else {
            System.out.println("答案错误");
        }
         
        break ;
    
      

    
    case 2:
        
         System.out.println(""+a+"*"+b+"=");
        int c = in.nextInt();
        out.println(a+"*"+b+"="+c);
        if (c == counter.multiply(a, b)) {
            sum += 10;
            System.out.println("答案正确");
        }
        else {
            System.out.println("答案错误");
        }
        break;
    case 3:
        
        
         
        while(b==0)
        {  b = (int) Math.round(Math.random() * 100);//满足分母不为0
        }
        while(a%b!=0)
        {
              a = (int) Math.round(Math.random() * 100);
              b = (int) Math.round(Math.random() * 100);
        }
        System.out.println(""+a+"/"+b+"=");
     int c0= in.nextInt();
    
     out.println(a+"/"+b+"="+c0);
     if (c0 == counter.divide(a, b)) {
         sum += 10;
         System.out.println("答案正确");
     }
     else {
         System.out.println("答案错误");
     }
    
     break;
     

    }
    }
    System.out.println("totlescore:"+sum);
    out.println(sum);
    
    out.close();
    }
    }
package fghjg;
public class yunsuan <T>{
    private T a;
    private T b;
    public void yunsaun()
    {
        a=null;
        b=null;
    }
    public void yunsuan(T a,T b)
    {
        this.a=a;
        this.b=b;
    }
   public int plus(int a,int b)
   {
       return a+b;
       
   }
   public int minus(int a,int b)
   {
    return a-b;
       
   }
   public int multiply(int a,int b)
   {
       return a*b;
   }
   public int divide(int a,int b)
   {
       if(b!=0  && a%b==0)
       return a/b;
       else
           return 0;
   }
   }

三、实验总结:

        本章我们学习了泛型程序设计技术,理解了泛型概念,掌握了泛型类的定义与使用和泛型方法的声明与使用。在验证实验中,通过对代码的解读,更好的学习了泛型程序<T>的使用,虽然不是很熟练,但还是做出来了,感觉依旧存在些小问题,在接下来的实验中要更好的解决。

猜你喜欢

转载自www.cnblogs.com/dhlll/p/9903334.html