李晓菁201771010114《面向对象程序设计(Java)》第十周学习总结

一:理论部分

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

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

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

4.泛型类可以有多个类型变量。例如:

public class Pair<T, U> { … }

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

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

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

7.泛型接口的定义:

public interface IPool <T>
{
T get();
int add(T t);

}

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

上述声明规定了NumberGeneric类所能处理的泛型变量类型,需和Number有继承关系。

extends关键字所声明的上界既可以是一个类,也可以是一个接口。

(2)定义泛型变量的下界:List<? super CashCard> cards = new ArrayList<T>();

下界说明:通过super关键字可以固定泛型参数的类型为某种类型或者其超类。

档程序希望为一个方法的参数限定时,通常可以使用下限通配符。

 9.通配符类型:“?”符号标明参数的类型可以是任何一种类型,他和参数T的含义是有区别的,T表示一种未知类型,而?标明任何一种类型。

这种通配符一般有以下三种用法:(1)单独的?:用于表示任何类型。

(2)?extends type:表示带有上界

(3)?super type:表示带有下界

10.pair与pair<?>de区别在于:可以用任意object对象调用原始的pair类的setobject方法。

二:实验部分:

实验十  泛型程序设计技术

实验时间 2018-11-1

1、实验目的与要求

(1) 理解泛型概念;

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

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

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

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

2、实验内容和步骤

实验1: 导入第8章示例程序,测试程序并进行代码注释。(以下三个测试程序中的pair类都相同,只需将三个程序定义在同一个包中,即可共用)

测试程序1:(在以下测试程序中,不再赘述主类pair类)

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

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

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

package pair1;

/**
 * @version 1.00 2004-05-10
 * @author Cay Horstmann
 */
public class Pair<T>//一个pair泛型类,引入一个类型变量T,该类可以有多个类型变量。 
{
   private T first;//类型变量T指定方法的返回类型以及域和局部变量的类型。
   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; }
}
pair
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" };//默认比较ASCII码值
      Pair<String> mm = ArrayAlg.minmax(words);//用具体类型替换类型变量T,即可实例化泛型类型。
      //通过类名调用方法,该方法为静态的。
      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)//stringPair类对象
   {
      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);//两个域可以使用不同的类型
   }
}
test1

测试程序2:

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

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

l 掌握泛型方法、泛型变量限定的定义及用途。

package pair2;

import java.time.*;//比较日期的大小调用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);//用LocateDate实例化泛型类型
      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) //为确信有compareTo方法,将T限制为实现Comparable接口,
   //加了上界约束的泛型方法
   {
      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);
   }
}
test2

测试程序3:

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

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

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<>();//也可用Mannager,因为Employee类是他的父类,在此可直接用它的父类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类
   {
      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)//有下限的通配符,表明它的下限是Manager类
   {
      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)//pair<?>,表示可以用任何Object对象调用原始的pair类的setobject方法。
   {
      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);
   }
}
test3
package pair3;

public class Manager extends Employee//mannager作为一个子类继承自它的父类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);//super调用超类中的一些方法
      bonus = 0;
   }

   public double getSalary()
   { 
      double baseSalary = super.getSalary();
      return baseSalary + bonus;
   }

   public void setBonus(double b)
   {  
      bonus = b;
   }

   public double getBonus()
   {  
      return bonus;
   }
}
Manager
package pair3;

import java.time.*;

public class Employee//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;
   }
}
Employee

实验2:编程练习:

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

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

 总结:(1)该程序有两个类构成,一个主类,

package text8;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;

public class Xinxi {
    private static ArrayList<Student> studentlist;

    
    public static  void main(String[] args) {
        studentlist = new ArrayList<>();
        Scanner scanner = new Scanner(System.in);
        File file = new File("D:\\身份证号\\身份证号.txt");
        try {
            FileInputStream fis = new FileInputStream(file);
            BufferedReader in = new BufferedReader(new InputStreamReader(fis));
            String temp = null;
            while ((temp = in.readLine()) != null) {

                Scanner linescanner = new Scanner(temp);

                linescanner.useDelimiter(" ");
                String name = linescanner.next();
                String number = linescanner.next();
                String sex = linescanner.next();
                String age = linescanner.next();
                String province = linescanner.nextLine();
                Student student = new Student();
                student.setName(name);
                student.setnumber(number);
                student.setsex(sex);
                int a = Integer.parseInt(age);
                student.setage(a);
                student.setprovince(province);
                studentlist.add(student);

            }
        } catch (FileNotFoundException e) {//添加的异常处理语句try{   }catch{   }语句
            System.out.println("所找信息文件找不到");
            e.printStackTrace();
        } catch (IOException e) {
            System.out.println("所找信息文件读取错误");//采取积极方法捕获异常,并将异常返回自己所设定的打印文字
            e.printStackTrace();
        }
        boolean isTrue = true;
        while (isTrue) {
            System.out.println("选择你的操作,输入正确格式的选项");
            System.out.println("1按姓名字典序输出人员信息");
            System.out.println("2.查询最大和最小年龄的人员信息");

            System.out.println("3.寻找老乡");
            System.out.println("4.寻找年龄相近的人的信息");

            System.out.println("5.退出");
            String n = scanner.next();
            switch (n) {
            case "1":
                Collections.sort(studentlist);
                System.out.println(studentlist.toString());
                break;
            case "2":
                int max = 0, min = 100;
                int j, k1 = 0, k2 = 0;
                for (int i = 1; i < studentlist.size(); i++) {
                    j = studentlist.get(i).getage();
                    if (j > max) {
                        max = j;
                        k1 = i;
                    }
                    if (j < min) {
                        min = j;
                        k2 = i;
                    }

                }
                System.out.println("年龄最大:" + studentlist.get(k1));

                System.out.println("年龄最小:" + studentlist.get(k2));
                break;
            case "3":
                System.out.println("家乡在哪里?");
                String find = scanner.next();
                String place = find.substring(0, 3);
                for (int i = 0; i < studentlist.size(); i++) {
                    if (studentlist.get(i).getprovince().substring(1, 4).equals(place))
                        System.out.println("同乡" + studentlist.get(i));
                }
                break;

            case "4":
                System.out.println("年龄:");
                int yourage = scanner.nextInt();
                int near = agenear(yourage);
                int value = yourage - studentlist.get(near).getage();
                System.out.println("" + studentlist.get(near));
                break;
            case "5":
                isTrue = false;
                System.out.println("退出程序!");
                break;
            default:
                System.out.println("输入有误");

            }
        }
    }

    public static int agenear(int age) {
        int j = 0, min = 53, value = 0, flag = 0;
        for (int i = 0; i < studentlist.size(); i++) {
            value = studentlist.get(i).getage() - age;
            if (value < 0)
                value = -value;
            if (value < min) {
                min = value;
                flag = i;
            }
        }
        return flag;
    }

}
xinxi

一个student类,该类实现了一个接口。

package text8;

public  class Student implements Comparable<Student> {

    private String name;
    private String number;
    private String sex;
    private String province;
    private int age;

    public void setName(String name) {
        // TODO 自动生成的方法存根
        this.name = name;

    }

    public String getName() {
        // TODO 自动生成的方法存根
        return name;
    }

    public void setnumber(String number) {
        // TODO 自动生成的方法存根
        this.number = number;
    }

    public String getNumber() {
        // TODO 自动生成的方法存根
        return number;
    }

    public void setsex(String sex) {
        // TODO 自动生成的方法存根
        this.sex = sex;
    }

    public String getsex() {
        // TODO 自动生成的方法存根
        return sex;
    }

    public void setprovince(String province) {
        // TODO 自动生成的方法存根
        this.province = province;
    }

    public String getprovince() {
        // TODO 自动生成的方法存根
        return province;
    }

    public void setage(int a) {
        // TODO 自动生成的方法存根
        this.age = age;
    }

    public int getage() {
        // TODO 自动生成的方法存根
        return age;
    }

    public int compareTo(Student o) {
        return this.name.compareTo(o.getName());
    }

    public String toString() {
        return name + "\t" + sex + "\t" + age + "\t" + number + "\t" + province + "\n";
    }
}
student

(2)在该程序中添加异常处理语句。采用积极抛出异常的模式,处理程序中可能会出现的异常。

(3)目前程序设计存在的困难是,可以将一个模块一个模块的写出来,但不知道该怎么将这些模块组织起来成一个完整的程序。

还有在程序运行结果出现一些不该出现的符号时,不知道该如何准确的修改。

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

总结:(1)该程序有两个类构成,一个主类,

package 第九周;
import java.util.Random;
import java.util.Scanner;
import java.io.FileNotFoundException;
import java.io.PrintWriter;

    public class Demo {
        public static void main(String[] args) {
            // 用户的答案要从键盘输入,因此需要一个键盘输入流
            //Scanner in = new Scanner(System.in);
            yunsuan counter = new yunsuan  ();
            PrintWriter out = null;
            
            try {
                out = new PrintWriter("D:\\text.txt");
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            int sum = 0;
            // 通过循环生成10道题
            for (int i = 0; i < 10; i++) {
            
                
                int a = (int) Math.round(Math.random() * 10);
                int b = (int) Math.round(Math.random() * 10);
                
                Scanner in1 =new Scanner(System.in);
                
                
                switch((int)(Math.random()*4))
                
                {
                
                case 1:
                System.out.println( ""+a+"+"+b+"=");
                
                int c1 = in1.nextInt();
                out.println(a+"+"+b+"="+c1);
                if (c1 == counter.add(a, b)) {
                    sum += 10;
                    System.out.println("恭喜答案正确");
                }
                else {
                    System.out.println("抱歉答案错误");
                }
                
                break ;
                case 2:
                System.out.println(i + ": " + a + "-" + b + "=");
                int c2 = in1.nextInt();
                out.println(a + "-" + b + "=" + c2);
                if (c2 == counter.reduce(a, b)) {
                    sum += 10;
                    System.out.println("恭喜答案正确");
                } else {
                    System.out.println("抱歉答案错误");
                }
                break;
                case 3:
                System.out.println(i + ": " + a + "*" + b + "=");
                int c3 = in1.nextInt();
                out.println(a + "*" + b + "=" + c3);
                if (c3 == counter.multiplication(a, b)) {
                    sum += 10;
                    System.out.println("恭喜答案正确");
                } else {
                    System.out.println("抱歉答案错误");
                }
                break;
                case 4:
                System.out.println(""+a+"/"+b+"=");
                while(b==0)
                {  b = (int) Math.round(Math.random() * 100);
                }
             int c4= in1.nextInt();
             out.println(a+"/"+b+"="+c4);
             if (c4 == counter.devision(a, b)) {
                 sum += 10;
                 System.out.println("恭喜答案正确");
             }
             else {
                 System.out.println("抱歉答案错误");
             }
             break;
             }
            }
            
                System.out.println("总分:"+sum);
                out.println(sum);
                
                out.close();
                }
                }
    

            
            
demo

一个用户自定义类

package 第九周;

public class yunsuan {

    public int multiplication(int a, int b) {
        // TODO 自动生成的方法存根
        return a*b;
    }

    public int add(int a, int b) {
        // TODO 自动生成的方法存根
        return a+b;
    }

    public int reduce(int a, int b) {
        // TODO 自动生成的方法存根
        if((a-b)>0)
        return a-b;
        else
            return 0;
    }

    public int devision(int a, int b) {
        // TODO 自动生成的方法存根
        if(b!=0)
        return a/b;
        else
            return 0;
    }

}
yunsuan

(2)存在的困难是,有些运算超出小学生的计算范围,当回答正确时,会生成10道四则运算习题,当有一个回答不正确时,生成的四则运算习题不是十道。

将生成的十道四则运算题目保存在txt文档中。

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

package 第九周;
import java.util.Random;
import java.util.Scanner;
import java.io.FileNotFoundException;
import java.io.PrintWriter;

    public class Demo {
        public static void main(String[] args) {
            // 用户的答案要从键盘输入,因此需要一个键盘输入流
            Scanner in = new Scanner(System.in);
            yunsuan counter = new yunsuan  ();
            PrintWriter out = null;
            
            try {
                out = new PrintWriter("D:\\text.txt");
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            int sum = 0;
            // 通过循环生成10道题
            for (int i = 0; i < 10; i++) {
            
                
                int a = (int) Math.round(Math.random() * 100);
                int b = (int) Math.round(Math.random() * 100);
                
                //Scanner in1 =new Scanner(System.in);
                
                Random rand=new Random();
                switch((int)(Math.random()*4)+1)
                
                {
                
                case 1:
                System.out.println( ""+a+"+"+b+"=");
                
                int c= in.nextInt();
                out.println(a+"+"+b+"="+c);
                if (c == counter.add(a, b)) {
                    sum += 10;
                    System.out.println("恭喜答案正确");
                }
                else {
                    System.out.println("抱歉答案错误");
                }
                
                break ;
                case 2:
                    while (a<b) {
                        b = (int)Math.round(Math.random() * 100); ;
                        
                    }
                System.out.println(i + ": " + a + "-" + b + "=");
                int c1 = in.nextInt();
                out.println(a + "-" + b + "=" + c1);
                if (c1 == counter.reduce(a, b)) {
                    sum += 10;
                    System.out.println("恭喜答案正确");
                } else {
                    System.out.println("抱歉答案错误");
                }
                break;
                case 3:
                System.out.println(i + ": " + a + "*" + b + "=");
                int c2 = in.nextInt();
                out.println(a + "*" + b + "=" + c2);
                if (c2 == counter.multiplication(a, b)) {
                    sum += 10;
                    System.out.println("恭喜答案正确");
                } else {
                    System.out.println("抱歉答案错误");
                }
                break;
                case 4:
                
                a = b + (int) Math.round(Math.random() * 100);
                while(b==0)
                {  b = (int) Math.round(Math.random() * 100);
                }
                while (a%b==0) {
                     a= (int) Math.round(Math.random() * 100);    
                    
                }
                System.out.println(""+a+"/"+b+"=");
             int c3= in.nextInt();
             out.println(a+"/"+b+"="+c3);
             if (c3 == counter.devision(a, b)) {
                 sum += 10;
                 System.out.println("恭喜答案正确");
             }
             else {
                 System.out.println("抱歉答案错误");
             }
             break;
             }
            }
            
                System.out.println("总分:"+sum);
                out.println(sum);
                
                out.close();
                }
                }
    

            
            
demo
package 第九周;

public class yunsuan<T>{
    private T a;
    private T b;
    public yunsuan() {
        a=null;
        b=null;
    }

    public int multiplication(int a, int b) {
        // TODO 自动生成的方法存根
        return a*b;
    }

    public int add(int a, int b) {
        // TODO 自动生成的方法存根
        return a+b;
    }

    public int reduce(int a, int b) {
        // TODO 自动生成的方法存根
        if((a-b)>0)//保证两数相减不会是负数
        return a-b;
        else
            return 0;
    }
    
    public int devision(int a, int b) {
        // TODO 自动生成的方法存根
        if (b != 0 && a%b==0)//保证是整除
        return a/b;
        else
            return 0;
    }

}
yunsuan

三:实验总结:通过本周的学习,掌握了泛型类的定义,以及泛型方法的声明,还有泛型接口的定义,以及对泛型变量的限定。

但在用泛型类写程序时还是有一点点的困难。在学长的指导帮助下学会了如何阅读别人的程序,并用快捷方法进入某一个类去读它的定义。

猜你喜欢

转载自www.cnblogs.com/li-xiaojing/p/9749682.html