• 201771010106东文财《面向对象程序设计(java)》实验10


    实验十  泛型程序设计技术

    实验时间 2018-11-4

    一、理论知识

    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、 类定义中的类型变量用于指定方法的返回类型以及域、局部变量的类型。

    8、 泛型方法

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

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

    二、实验部分

    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> //定义公共类,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" };
          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++)//for循环语句
          {
             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 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);
       }
    }

    实验结果:

    测试程序3:

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

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

    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;
       }
    }
    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)
       {
          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)
       {
          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编程练习:

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

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

     总体结构:

    类people

    1、读入文件等

    2、定义了查找人员信息的方法

    3、分5个case来分别说年龄大小、等。

    出现问题:

    过程中出现了很多问题,主要原因还是在于自己的粗心和对一些知识的掌握不够,不过在和同学们的交流和学习中得以解决,以后我会接续努力的。

    package gh;
        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.Scanner;
        import java.util.Collections;
    
        public class tt {
    
            public static People findPeopleByname(String name) {
                People flag = null;
                for (People people : peoplelist) {
                    if(people.getName().equals(name)) {
                        flag = people;
                    }
                }
                return flag;
    
            }
    
            public static People findPeopleByid(String id) {
                People flag = null;
                for (People people : peoplelist) {
                    if(people.getnumber().equals(id)) {
                        flag = people;
                    }
                }
                return flag;
    
            }
             
            private static ArrayList<People> agenear(int yourage) {
                // TODO Auto-generated method stub
                int j=0,min=53,d_value=0,k = 0;
                ArrayList<People> plist = new ArrayList<People>();
                for (int i = 0; i < peoplelist.size(); i++) {
                    d_value = peoplelist.get(i).getage() > yourage ? 
                            peoplelist.get(i).getage() - yourage : yourage - peoplelist.get(i).getage() ;
                    k = d_value < min ? i : k;
                    min = d_value < min ? d_value : min;
                }
                for(People people : peoplelist) {
                    if(people.getage() == peoplelist.get(k).getage()) {
                        plist.add(people);
                    }
                }
                return plist;
            }
    
            private static ArrayList<People> peoplelist; 
            
            public static void main(String[] args) //throws  IOException
            {
                peoplelist = new ArrayList<People>();
                Scanner scanner = new Scanner(System.in);
                File file = new File("D:\身份证号.txt");
                try {
                    FileInputStream files = new FileInputStream(file);
                    BufferedReader in = new BufferedReader(new InputStreamReader(files));
                    String temp = null;
                    while ((temp = in.readLine()) != null) {
                        
                        String[] information = temp.split("[ ]+");
                        People people = new People();
                        people.setName(information[0]);
                        people.setnumber(information[1]);
                        int A = Integer.parseInt(information[3]);
                        people.setage(A);
                        people.setsex(information[2]);
                        for(int j = 4; j<information.length;j++) {
                            people.setplace(information[j]);
                        }
                        peoplelist.add(people);
    
                    }
                } 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.输入你的年龄,查询身份证号.txt中年龄与你最近的人");
                    System.out.println("   5.查询人员中是否有你的同乡");
                    System.out.println("   6.退出");
                    System.out.println("******************************************");
                    int nextInt = scanner.nextInt();
                    switch (nextInt) {
                    case 1:
                        Collections.sort(peoplelist);
                        System.out.println(peoplelist.toString());
                        break;
                    case 2:
                        int max=0;
                        int j,k1 = 0;
                        for(int i=1;i<peoplelist.size();i++)
                        {
                            j = peoplelist.get(i).getage();
                           if(j>max)
                           {
                               max = j; 
                               k1 = i;
                           }
                          
                        }  
                        System.out.println("年龄最大:"+peoplelist.get(k1));
                        break;
                    case 3:
                        int min = 100;
                        int j1,k2 = 0;
                        for(int i=1;i<peoplelist.size();i++)
                        {
                            j1 = peoplelist.get(i).getage();
                            if(j1<min)
                            {
                                min = j1; 
                                k2 = i;
                            }
    
                         } 
                        System.out.println("年龄最小:"+peoplelist.get(k2));
                        break;
                    case 4:
                        System.out.println("年龄:");
                        int input_age = scanner.nextInt();
                        ArrayList<People> plist = new ArrayList<People>();
                        plist = agenear(input_age);
                        for(People people : plist) {
                            System.out.println(people.toString());
                        }
                        break;
                    case 5:
                        System.out.println("请输入省份");
                        String find = scanner.next();        
                        for (int i = 0; i <peoplelist.size(); i++) 
                        {
                            String [] place = peoplelist.get(i).getplace().split("	");
                            for(String temp : place) {
                                if(find.equals(temp)) {
                                    System.out.println("你的同乡是    "+peoplelist.get(i));
                                    break;
                                }
                            }
                            
                        } 
                        break;
                    case 6:
                        isTrue = false;
                        System.out.println("byebye!");
                        break;
                    default:
                        System.out.println("输入有误");
                    }
                }
            }
    
        }
    }

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

    总体结构:

    类main

    1、程序中的文件读取等

    出现问题:

    1.没有定义文件输出的路径,找输出文件不简单。

    解决方法:只需定义路径即可如:

    ("E:\壁纸\海贼王\text.txt");
    package rt;
    
    
        import java.io.FileNotFoundException;
        import java.io.PrintWriter;
        import java.util.Scanner;
        public class tt {
            public static void main(String[] args) {
                Scanner in = new Scanner(System.in);
                tt1 computing=new tt1();
                PrintWriter output = null;
                try {
                    output = new PrintWriter("tt.txt");
                } catch (Exception e) {
                }
                int sum = 0;
    
                for (int i = 1; i < 11; i++) {
                    int a = (int) Math.round(Math.random() * 100);
                    int b = (int) Math.round(Math.random() * 100);
                    int s = (int) Math.round(Math.random() * 3);
                switch(s)
                {
                   case 1:
                       System.out.println(i+": "+a+"/"+b+"=");
                       while(b==0){  
                           b = (int) Math.round(Math.random() * 100); 
                           }
                       double c = in.nextDouble();
                       output.println(a+"/"+b+"="+c);
                       if (c == (double)computing.division(a, b)) {
                           sum += 10;
                           System.out.println("正确");
                       }
                       else {
                           System.out.println("错误");
                       }
                    
                       break;
                    
                   case 2:
                       System.out.println(i+": "+a+"*"+b+"=");
                       int c1 = in.nextInt();
                       output.println(a+"*"+b+"="+c1);
                       if (c1 == computing.multiplication(a, b)) {
                           sum += 10;
                           System.out.println("正确");
                       }
                       else {
                           System.out.println("错误");
                       }
                       break;
                   case 3:
                       System.out.println(i+": "+a+"+"+b+"=");
                       int c2 = in.nextInt();
                       output.println(a+"+"+b+"="+c2);
                       if (c2 == computing.addition(a, b)) {
                           sum += 10;
                           System.out.println("正确");
                       }
                       else {
                           System.out.println("错误");
                       }
                       
                       break ;
                   case 4:
                       System.out.println(i+": "+a+"-"+b+"=");
                       int c3 = in.nextInt();
                       output.println(a+"-"+b+"="+c3);
                       if (c3 == computing.subtraction(a, b)) {
                           sum += 10;
                           System.out.println("正确");
                       }
                       else {
                           System.out.println("错误");
                       }
                       break ;
    
                       } 
            
                  }
                System.out.println("成绩:"+sum+"分");
                output.println("成绩:"+sum+"分");
                output.close();
                 
            }
        }
        class tt1
        {
               private int a;
               private int b;
                public int  addition(int a,int b)
                {
                    return a+b;
                }
                public int  subtraction(int a,int b)
                {
                    if((a-b)<0)
                        return 0;
                    else
                    return a-b;
                }
                public int   multiplication(int a,int b)
                {
                    return a*b;
                }
                public int   division(int a,int b)
                {
                    if(b!=0)
                    return a/b;    
                    else
                return 0;
                }
    
                
        }

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

    package hh;

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

    public jj(T a, T b) {
    this.a = a;
    this.b = b;
    }
    public int jj1(int a,int b)
    {
    return a+b;
    }
    public int jj2(int a,int b)
    {
    return a-b;
    }
    public int jj3(int a,int b)
    {
    return a*b;
    }
    public int jj4(int a,int b)
    {
    if(b!=0)
    return a/b;
    else return 0;
    }

    }

    package hh;
        import java.io.FileNotFoundException;
        import java.io.PrintWriter;
        import java.util.Scanner;
    
    
        public class kk {
            public static void main(String[] args) {
    
                Scanner in = new Scanner(System.in);
                jj counter=new jj();
                PrintWriter out = null;
                try {
                    out = new PrintWriter("E:\壁纸\海贼王\text.txt");
                } catch (FileNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                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 m= (int) Math.round(Math.random() * 3);
    
                    
                   switch(m)
                   {
                   case 0:
                       System.out.println(a + "+" + b + "=");
                       int d0 = in.nextInt();
                       out.println(a + "+" + b + "=" + d0);
                       if (d0 == counter.jj1(a, b)) {
                           sum += 10;
                           System.out.println("正确");
                       } else {
                           System.out.println("错误");
                       }
                       break;
                   case 1:
                       while (a < b) {
                           int x = a;
                           a = b;
                           b = x;
                       }
                       System.out.println(a + "-" + b + "=");
                       int c1 = in.nextInt();
                       out.println(a + "-" + b + "=" + c1);
                       if (c1 == counter.jj2(a, b)) {
                           sum += 10;
                           System.out.println("正确");
                       } else {
                           System.out.println("错误");
                       }
                       break;
                   case 2:
                       System.out.println(a + "*" + b + "=");
                       int c2 = in.nextInt();
                       out.println(a + "*" + b + "=" + c2);
                       if (c2 ==counter.jj3(a, b)) {
                           sum += 10;
                           System.out.println("正确");
                       } else {
                           System.out.println("错误");
                       }
                       break;
                   case 3:
                       while (b == 0 || a % b != 0) {
                           a = (int) Math.round(Math.random() * 100);
                           b = (int) Math.round(Math.random() * 100);
                       }
                       System.out.println(a + "/" + b + "=");
                       int c3 = in.nextInt();
                       out.println(a + "/" + b + "=" + c3);
                       if (c3 == counter.jj4(a, b)) {
                           sum += 10;
                           System.out.println("正确");
                       } else {
                           System.out.println("错误");
                       }
                       break;
    
                   }
    
             
        }
                System.out.println("成绩"+sum);
                out.println("成绩:"+sum);
                 out.close();
    
                 
            }
            }

    实验结果:

    实验总结:

       本章我们主要学习了泛型程序设计,使用泛型机制编写的程序代码要比那些杂乱地使用Object变量,然后再进行强行类型转换的代码具有更好的安全性和可读性。反省对于集合类尤其有用。通过课后一些简单程序的编译,运行,知道了如何定义简单的泛型类,和他的一些用法。希望在以后的编程中我会多多的用到这些学过的知识。

  • 相关阅读:
    云计算、大数据和人工智能简单概述
    Linux 文件管理命令语法、参数、实例全汇总(一)
    C#之继承
    类和结构(二)
    类和结构(一)
    C#基础语法(二)
    C#基础语法(一)
    dotnet体系结构
    九卷读书:刘润商学院学习笔记1
    Linux内存管理
  • 原文地址:https://www.cnblogs.com/D980321/p/9903466.html
Copyright © 2020-2023  润新知