zoukankan      html  css  js  c++  java
  • 实验十 泛型程序设计技术

    实验十  泛型程序设计技术

    实验时间 2018-11-1

    基础知识:

    1 什么是泛型程序设计?
    . JDK 5.0 中增加的泛型类型,是Java 语言中类型安全的一次重要改进。
    . 泛型:也称参数化类型(parameterized type),就是在定义类、接口和方法时,通过类型参数指示将要处理的对象类型。(如ArrayList类)
    . 泛型程序设计(Generic programming):编写代码可以被很多不同类型的对象所重用。

    2 泛型类的定义 :一个泛型类(generic class)就是具有一个或多个类型变量的类,即创建用类型作为参数的类。如一个泛型类定义格式如下:
    class Generics<K,V>其中的K和V是类中的可变类型参数。
    Pair类引入了一个类型变量T,用尖括号(<>)括起来,并放在类名的后面。泛型类可以有多个类型变量。例如:
    public class Pair<T, U> { … }类定义中的类型变量用于指定方法的返回类型以及域、局部变量的类型。�

    3 泛型方法的声明: 除了泛型类外,还可以只单独定义一个方法作为泛型方法,用于指定方法参数或者返回值为泛型类型,留待方法调用时确定。
    – 泛型方法可以声明在泛型类中,也可以声明在普通类中。

    4 泛型变量的限定:public class NumberGeneric< T extends Number>泛型变量上界的说明,上述声明规定了NumberGeneric类所能处理的泛型变量类型需和Number有继承关系;extends关键字所声明的上界既可以是一个类,也可以是一个接口;

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

    5 泛型类的约束与局限性(*)
     不能用基本类型实例化类型参数
     运行时类型查询只适用于原始类型
     不能抛出也不能捕获泛型类实例
     参数化类型的数组不合法
     不能实例化类型变量
     泛型类的静态上下文中类型变量无效
     注意擦除后的冲突

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

    实验内容

    1、实验目的与要求

    (1) 理解泛型概念;

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

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

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

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

    2、实验内容和步骤

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

    测试程序1:

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

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

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

    package pair1;
    
    /**
     * @version 1.00 2004-05-10
     * @author Cay Horstmann
     */
    //Pair泛型类
    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; }
    }
    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" };
          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)//返回值为实例化的类对象
       {
          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];//若比较结果大于0,则表明此时的min不是最小的,将新的字符串存进min
             if (max.compareTo(a[i]) < 0) max = a[i];//和上面min的 比较方法一样
          }
          return new Pair<>(min, max);//返回新的Pair类对象
       }
    }
    PairTest1

    测试程序2:

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

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

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

    package pair1;
    
    /**
     * @version 1.00 2004-05-10
     * @author Cay Horstmann
     */
    //Pair泛型类
    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; }
    }
    Pair
    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);//定义Pair类对象mm
          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) //将T限制为 实现了Comparable接口的类,则泛型的minmax方法只能被实现了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];//若比较结果大于0,则表明此时的min不是最小的,将新的字符串存进min
             if (max.compareTo(a[i]) < 0) max = a[i];//和上面min的 比较方法一样
          }
          return new Pair<>(min, max);//返回新的Pair类对象
       }
    }
    PairTest2

    测试程序3:

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

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

    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;
       }
    }
    Employee
    package pair3;
    
    public class Manager extends Employee//子类为manager,父类为emploee
    {  
       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;
       }
    }
    Manager
    package pair3;
    
    /**
     * @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; }
    }
    Pair
    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)//?是通配符,表明参数的类型是上界为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)//?是通配符,表明参数的类型是下界为manager的任何一种类型
       {
          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)
       {
          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);
       }
    }
    PairTest3

    实验2:编程练习:

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

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

    1.程序总体结构说明:

    主类为xinxi,子类为Student

    2.模块说明:

    首先是文件的读入操作,然后利用switch语句对需要处理的几种情况进行了分别处理。

    package xinxi;
    
    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.Scanner;
    
    public class xinxi{
        private static ArrayList<Student> studentlist;
        public static void main(String[] args) {
            studentlist = new ArrayList<>();
            @SuppressWarnings("resource")
            Scanner scanner = new Scanner(System.in);
            File file = new File("F:\身份证号.txt");
            try {
                FileInputStream fis = new FileInputStream(file);
                @SuppressWarnings("resource")
                BufferedReader in = new BufferedReader(new InputStreamReader(fis));
                String temp = null;
                while ((temp = in.readLine()) != null) {
                    
                    @SuppressWarnings("resource")
                    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) {
                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.查找你的同乡");
                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("年龄:");
                    int yourage = scanner.nextInt();
                    int near=agenear(yourage);
                    @SuppressWarnings("unused") int value=yourage-studentlist.get(near).getage();
                    System.out.println("和你年龄相近的是"+studentlist.get(near));
                    break;
    
                case "4":
                     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;
    
                }
            }
        }
            public static int agenear(int age) {      
            @SuppressWarnings("unused")
            int j=0,min=53,value=0,k=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;
                    k=i;
                 } 
              }    
             return k;         
          
    
    }
    
    
    }
    xinxi

    这一部分要是对学生信息文件的具体处理。

    package xinxi;
    
    
    
    public class Student implements Comparable<Student> {
    
        private String name;
        private String number ;
        private String sex ;
        private int age;
        private String province;
       
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public String getnumber() {
            return number;
        }
        public void setnumber(String number) {
            this.number = number;
        }
        public String getsex() {
            return sex ;
        }
        public void setsex(String sex ) {
            this.sex =sex ;
        }
        public int getage() {
    
            return age;
            }
        public void setage(int age) {
            this.age= age;
            }
    
        public String getprovince() {
            return province;
        }
        public void setprovince(String province) {
            this.province=province ;
        }
    
        public int compareTo(Student o) {
           return this.name.compareTo(o.getName());
        }
    
        public String toString() {
            return  name+"	"+sex+"	"+age+"	"+number+"	"+province+"
    ";
        }    
    }
    Student

    3.目前程序设计存在的困难与问题:在文件的读取方面存在一定的问题,此外数据处理方面的转换也有相应的问题。

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

    1.程序总体结构说明

    2.模块说明:

    这一部分主要完成了随机生成数和利用switch语句对四则运算的基本操作

    package jisuan;
    
    import java.util.Scanner;
    public class Jisuan {
        public static void main(String[] args) {
            
            Scanner in = new Scanner(System.in);
            
            int sum = 0;
            
            for (int i = 0; i < 10; i++) {
    
                int a = (int) Math.round(Math.random() * 100);
                int b = (int) Math.round(Math.random() * 100);
                int d = (int) Math.round(Math.random() * 3);
                switch (d) {
                case 0:
                    if(b!=0) {
                    System.out.println(a + "/" + b + "=");
    
                    int c = in.nextInt();
                    
                    if (c == a / b) {
                        sum += 10;
                        System.out.println("恭喜答案正确");
                    } else {
                        System.out.println("抱歉,答案错误");
                    }
                    }else {
                        System.out.println("此表达式错误");
                    }
                    
                    break;
                case 1:
    
                    System.out.println(a + "+" + b + "=");
                    int c0 = in.nextInt();
                    if (c0 == a + b) {
                        sum += 10;
                        System.out.println("恭喜答案正确");
                    } else {
                        System.out.println("抱歉,答案错误");
                    }
                    break;
                case 2:
    
                    System.out.println(a + "-" + b + "=");
                    int c1 = in.nextInt();
                    if (c1 == a + b) {
                        sum += 10;
                        System.out.println("恭喜答案正确");
                    } else {
                        System.out.println("抱歉,答案错误");
                    }
                    break;
                case 3:
    
                    System.out.println(a + "*" + b + "=");
                    int c2 = in.nextInt();
                    if (c2 == a + b) {
                        sum += 10;
                        System.out.println("恭喜答案正确");
                    } else {
                        System.out.println("抱歉,答案错误");
                    }
                    break;
                }
            }
            
            System.out.println("你的得分为" + sum);
    
        }
    }
    Jisuan

    shuchu部分主要完成了将程序运算结果以txt文件输出

    package jisuan;
    
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.PrintWriter;
    import java.util.Scanner;
    
    public class shuchu {
        public static void main(String[] args) {
            Scanner in = new Scanner(System.in);
            Jisuan counter = new Jisuan();
            PrintWriter out = null;
            try {
                out = new PrintWriter("shu.txt");
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
    
            }
    }
    }
    shuchu

    3.目前程序设计存在的困难与问题:将程序运算结果以txt文件输出方面存在问题。

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

    代码如下:

    package jisuan;
    
    import java.io.*;
    import java.io.PrintWriter;
    import java.util.Scanner;
    
    public class Jisuan {
        public static void main(String[] args) {
    
            Scanner in = new Scanner(System.in);
    
            PrintWriter output = null;
            try {
                output = new PrintWriter("text.txt");
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            int sum = 0;
            for (int i = 1; i <= 10; i++) {
                int a = (int) Math.round(Math.random() * 100);
                int b = (int) Math.round(Math.random() * 100);
                int m = (int) Math.round(Math.random() * 4);
                switch (m) {
                case 1:
                    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 c1 = in.nextInt();
                    output.println(a + "/" + b + "=" + c1);
                    if (c1 == a / b) {
                        System.out.println("恭喜答案正确");
                        sum += 10;
                    } else {
                        System.out.println("抱歉,答案错误");
                    }
    
                    break;
    
                case 2:
                    System.out.println( a + "*" + b + "=");
                    int c2 = in.nextInt();
                    output.println(a + "*" + b + "=" + c2);
                    if (c2 == a * b) {
                        System.out.println("恭喜答案正确");
                        sum += 10;
                    } else {
                        System.out.println("抱歉,答案错误");
                    }
                    break;
                case 3:
                    System.out.println( a + "+" + b + "=");
                    int c3 = in.nextInt();
                    output.println(a + "+" + b + "=" + c3);
                    if (c3 == a + b) {
                        System.out.println("恭喜答案正确");
                        sum += 10;
                    } else {
                        System.out.println("抱歉,答案错误");
                    }
    
                    break;
                case 4:
                    while (a < b) {
                        a = (int) Math.round(Math.random() * 100);
                    }
                    System.out.println( a + "-" + b + "=");
                    int c4 = in.nextInt();
                    output.println(a + "-" + b + "=" + c4);
                    if (c4 == a - b) {
                        System.out.println("恭喜答案正确");
                        sum += 10;
                    } else {
                        System.out.println("抱歉,答案错误");
                    }
                    break;
    
                }
    
            }
            System.out.println("成绩" + sum);
            output.println("成绩" + sum);
            output.close();
        }
    }
    Jisuan
    package jisuan;
    public class math<T> {
        private T a;
        private T b;
    
        public int add(int a, int b) {
            return a + b;
        }
    
        public int reduce(int a, int b) {
            return a - b;
        }
    
        public int multiplication(int a, int b) {
            return a * b;
        }
    
        public int division(int a, int b) {
            if (b != 0 && a % b == 0)
                return a / b;
            else
                return 0;
        }
    }
    math

    实验结果如下图

    实验总结:理解掌握了泛型类的定义与使用,泛型方法的声明与使用;泛型接口的定义与实现;此外,对上次实验的总结反思方面,从中发现了自己的很多不足,尤其是四则运算的编程,相比上次实验,从中认识到了很多不足,通过改正,完善了上次没有将程序运行结果以txt文件输出的不足。而且通过这次对泛型类的学习,将其与四则运算的编程结合起来,使的四则运算的程序更加完整,可以实现各种数据类型的运算。有了很大的提升,让我意识到要不断对之前学过的内容进行反思总结,不断完善之前的不足,这样才有提升。

  • 相关阅读:
    WPF 碰撞检测
    设置完在Canvas的位置后,控件HitTest不响应的问题
    Comparing the Performance of .NET Serializers(zz)
    Converting Stream to String and back…what are we missing?
    C# 序列化(Serialize)与反序列化(Deserialize)ZZ
    如何:从代码创建 UML 类图(ZZ)
    nginx 502 bad gateway
    mysql innodb_buffer_pool_size mysql占用内存大小和主从复制并行线程数量
    lvreduce -L 1000M /dev/vg0/lv0 表示最后缩减至多大,不是减少了多大
    nginx 4层tcp代理获取真实ip
  • 原文地址:https://www.cnblogs.com/zyan---/p/9890723.html
Copyright © 2011-2022 走看看