• 刘志梅 2017710101152《面向对象程序设计(java)》 第十周学习总结


    实验十  泛型程序设计技术

    实验时间 2018-11-1

    1、实验目的与要求

    (1)泛型程序设计:意味着编写的代码可以被很多不同类型的对象所重用。(ArrayList类可以聚集任何类型的对象)

    如果在其它地方,若将get的结果强制类型转换为String类型,就会产生一个错误;泛型类提供了更好地解决方案:类型参数(类型参数的魅力在于使得程序具有更好地可读性和安全性)。

    (2) 定义简单泛型类:一个泛型类就是具有一个或多个类型变量的类(泛型类可以有多个类型变量)。

    类定义中的类型变量指定方法的返回类型以及域和局部变量的类型。

    (3) 泛型方法泛型方法可以定义在普通类中,也可以定义在泛型类中。

    一个类型变量或通配符可以有多个限定;限定类型用“&”分隔,而逗号用来分隔类型变量;在java继承中,可以根据需要拥有多个接口超类型,但限定中至多有一个类。

    (4) 虚拟机没有泛型类行对象--所有对象都属于普通类;无论何时定义一个泛型类型,都自动提供了一个相应的原始类型(原始类型的名字就是删去类型参数后的泛型类型名)。

    原始类型用第一个限定的类型变量来替换,如果没有给定限定就用Object替换。

    当程序调用泛型方法时,如果擦除返回类型,编译器插入强制类型转换;当存取一个泛型域时也要插入强制类型转换。

    (5)类型擦除也会出现在泛型方法中;一个日期区间是一对LocalDate对象,并且需要覆盖这个方法来确保第二个值永远不小于第一个值。

    有关java泛型类转换的事实:虚拟机中没有泛型,只有普通的类和方法;所有的类型参数都用它们的限定类型替换;桥方法被合成来保持多态;为保持类型安全性,必要时插入强制类型转换。

    设计java泛型类型时,主要目标是允许泛型代码和遗留代码之间能够相互操作;在查看了警告之后,可以利用注解使之消失;注释必须放在生成这个警告的代码所在的方法之前。

    大多数限制都是由类型擦除引起的;不能用类型参数代替基本类型;虚拟机中的对象总有一个非泛型类型,因此,所有的类型查询只产生原始类型;java不支持泛型类型的数组。

    不能使用像new T(....),new T[....]或T.class这样的表达式中的类型变量(Class类本身是泛型)。

    就像不能实例化一个泛型实例一样,也不能实例化数组;如果数组仅仅作为一个类的私有实例域,就可以将这个数组声明为Object[],并且在获取元素时进行类型转换。

    不能在静态域或方法中引用类型变量;既不能抛出也不能捕获泛型类对象(实际上,甚至泛型类扩展Throwable都是不合法的,不过,在异常规范中使用类型变量是允许的);java处理异常的一个基本原则是,必须为所有受查异常提供一个处理器。

    通过使用泛型类、擦除和@SuppressWarnings注解,就能消除java类型系统的部分基本限制。

    当泛型类型被擦除时,无法创建引发冲突的条件;泛型规范说明还提到另外一个原则:“要想支持擦除的转换,就需要强行限制一个类或类型变量不能同时成为两个接口类型的子类,而这两个接口是同一接口的不同参数化”。

    (6)永远可以将参数化类型转换为一个原始类型;泛型类型可以扩展或实现其他的泛型类。

    (7)通配符类型中,允许类型参数变化;通配符限定于类型变量限定十分类似,但是,还有一个附加的能力,即可以指定一个超类型限定,可以为方法提供参数,但不能使用返回值;子类型限定的另一个常见的用法是作为一个函数式接口的参数类型。

    还可以使用无限定的通配符,例如Pair<?>;Pair<?>和Pair本质的不同在于:可以用任意的Object对象调用原始Pair类的setObject方法;通配符不是类型变量,因此,不能在编写代码中使用“?”作为一种类型。

    通配符捕获只有在许多限制的情况下才是合法的;编译器必须能够确信通配符表达的是单个、确定的类型。

    (8)反射允许你在运行时分析任意的对象(如果对象是泛型类的实例,关于泛型类型参数则得不到太多信息,因为他们会被擦除)。

    有时,匹配泛型方法中的Class<T>参数的类型变量很有实用价值;java泛型的卓越特性之一是在虚拟机中泛型类型的擦除;擦除的类仍然保留一些泛型祖先的微弱记忆。

    2、实验内容和步骤

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

    测试程序1:

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

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

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

    /**
     * @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                                      //类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];//字符串min=[0]
          String max = a[0];//字符串max=[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
       }
    }

    测试程序2

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

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

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

    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;//如果(a==null ||长度==0)返回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,结合程序运行结果理解程序;

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

    /**
     * @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;//如果(一个.长度==0)返回;
          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);// minmaxBonus(结果)
          PairAlg.swapHelper(result); // OK--swapHelper captures wildcard type
       }
       // Can't write public static <T super manager> ...不能写公共静态T超级经理
    }
    
    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总结(从程序总体结构说明、模块说明,目前程序设计存在的困难与问题三个方面阐述)。

     main类:将人员信息导入;编辑查找方法;分五个case进行

    package shen;
    
    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 Main {
        /**
         * 文件读取模块 利用ArrayList构造studentlist存放文件内容; 创建文件字符流,分类读取文件内容;try/catch语句捕获异常
         */
        private static ArrayList<Student> studentlist;
    
        public static void main(String[] args) {
            studentlist = new ArrayList<>();
            Scanner scanner = new Scanner(System.in);
            File file = new File("C:\Users\ASUS\Desktop\新建文件夹\身份证号.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) {
                System.out.println("学生信息文件找不到");
                e.printStackTrace();
                // 加入的捕获异常代码
            } catch (IOException e) {
                System.out.println("学生信息文件读取错误");
                e.printStackTrace();
                // 加入的捕获异常代码
            }
            /*
             * 1.根据实验要求,选择具体操作的模块,用switch语句具体的操作
             */
            boolean isTrue = true;
            while (isTrue) {
                System.out.println("选择你的操作,输入正确格式的选项");
                System.out.println("A.字典排序");
                System.out.println("B.输出年龄最大和年龄最小的人");
                System.out.println("C.寻找老乡");
                System.out.println("D.寻找年龄相近的人");
                System.out.println("F.退出");
                String m = scanner.next();
                switch (m) {
                case "A":
                    Collections.sort(studentlist);
                    System.out.println(studentlist.toString());
                    break;
                case "B":
                    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 "C":
                    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 "D":
                    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 "F":
                    isTrue = false;
                    System.out.println("退出程序");
                    break;
                default:
                    System.out.println("输入有误");
    
                }
            }
        }
    
        /*
         * 对年龄数据进行处理
         */
        public static int agenear(int age) {
            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;
        }
    
    }
    package shen;
    
    /*
     * 分类返回具体数据
    *利用接口技术比较name的大小
    *用toString方法返回数据
     */
    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) {
            // int a = Integer.parseInt(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() {  //用toString返回
            return name + "	" + sex + "	" + age + "	" + number + "	" + province + "
    ";
        }
    }

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

     判断代码是否正确;文件的读取;及四则运算。

    package demo;
    
    import java.io.FileNotFoundException;
    import java.io.PrintWriter;
    import java.util.Random;
    import java.util.Scanner;
    
    public class demo {
        public static void main(String[] args) {
    /**
    *文件输出模块
    *1.调用构造函数counter
    *2.创建文件字符流,将out中的内容设为空(null)
    *3.将out结果输出到test.txt中
    *4.try/catch模块捕获异常
    */
            Scanner in = new Scanner(System.in);
            yunsuan counter = new yunsuan();
            PrintWriter out = null;
            try {
                out = new PrintWriter("text.txt");
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    /**
    *四则运算生成模块
    *1.定义一个int型sum,计算成绩,并说明生成的运算类型
    *2.for语句,将{}内的内容循环10次,从而生成10道题目
    *3.随机生成int型a与b,范围在0到100以内;生成int型m,范围为1,2,3,4
    *4.利用switch语句,根据生成m的值,随机生成加减乘除四则运算
    *5.将循环结果输出到test.txt中
    */
            int sum = 0;
            System.out.println("随机生成的四则运算类型");
            System.out.println("类型1:除法");
            System.out.println("类型2:乘法");
            System.out.println("类型3:加法");
            System.out.println("类型4:减法");
            
            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;
                Random rand = new Random();
                m = (int) rand.nextInt(4) + 1;
                System.out.println("随机生成的四则运算类型:"+m);
    
                switch (m) {
                case 1:
                    System.out.println(i + ": " + a + "/" + b + "=");
    
                    while (b == 0) {
                        b = (int) Math.round(Math.random() * 100);
                    }
    
                    double c0 = in.nextDouble();
                    out.println(a + "/" + b + "=" + c0);
                    if (c0 == counter.division(a, b)) {
                        sum += 10;
                        System.out.println("right!");
                    } else {
                        System.out.println("error!");
                    }
    
                    break;
    
                case 2:
                    System.out.println(i + ": " + a + "*" + b + "=");
                    int c = in.nextInt();
                    out.println(a + "*" + b + "=" + c);
                    if (c == counter.multiplication(a, b)) {
                        sum += 10;
                        System.out.println("right!");
                    } else {
                        System.out.println("error!");
                    }
                    break;
                case 3:
                    System.out.println(i + ": " + a + "+" + b + "=");
                    int c1 = in.nextInt();
                    out.println(a + "+" + b + "=" + c1);
                    if (c1 == counter.add(a, b)) {
                        sum += 10;
                        System.out.println("right!");
                    } else {
                        System.out.println("error!");
                    }
                    break;
                case 4:
                    System.out.println(i + ": " + a + "-" + b + "=");
                    int c2 = in.nextInt();
                    out.println(a + "-" + b + "=" + c2);
                    if (c2 == counter.reduce(a, b)) {
                        sum += 10;
                        System.out.println("right!");
                    } else {
                        System.out.println("error!");
                    }
                    break;
                }
            }
            System.out.println("成绩" + sum);
            out.println("成绩:" + sum);
            out.close();
        }
    }

     

    package demo;
    
    public class yunsuan {
           private int a;
           private int 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) 
                    return a/b;
                else 
                    return 0;            
            }
    
    }

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

    package demo;
    
    import java.io.FileNotFoundException;
    import java.io.PrintWriter;
    import java.util.Random;
    import java.util.Scanner;
    
    public class demo {
        public static void main(String[] args) {
    /**
    *文件输出模块
    *1.调用构造函数counter
    *2.创建文件字符流,将out中的内容设为空(null)
    *3.将out结果输出到test.txt中
    *4.try/catch模块捕获异常
    */
            Scanner in = new Scanner(System.in);
            yunsuan counter = new yunsuan();
            PrintWriter out = null;
            try {
                out = new PrintWriter("test.txt");
            } catch (FileNotFoundException e) {
                System.out.println("文件夹输出失败");
                e.printStackTrace();
            }
    /**
    *四则运算生成模块
    *1.定义一个int型sum,计算成绩,并说明生成的运算类型
    *2.for语句,将{}内的内容循环10次,从而生成10道题目
    *3.随机生成int型a与b,范围在0到100以内;生成int型m,范围为1,2,3,4
    *4.利用switch语句,根据生成m的值,随机生成加减乘除四则运算
    *5.将循环结果输出到test.txt中
    */
            int sum = 0;
            System.out.println("随机生成的四则运算类型");
            System.out.println("类型1:除法");
            System.out.println("类型2:乘法");
            System.out.println("类型3:加法");
            System.out.println("类型4:减法");
    
            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;
                Random rand = new Random();
                m = (int) rand.nextInt(4) + 1;
                System.out.println("随机生成的四则运算类型:" + m);
    
                switch (m) {
                case 1:
                    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);
                        
                    }
                                    //若生成的除法式子必须能整除,且满足分母为0的条件,则a一定要大于b,且a模b的结果要为0。
                    System.out.println(i + ": " + a + "/" + b + "=");
    
                    int c0 = in.nextInt();
                    out.println(a + "/" + b + "=" + c0);
                    if (c0 == counter.division(a, b)) {
                        sum += 10;
                        System.out.println("right!");
                    } else {
                        System.out.println("error!");
                    }
    
                    break;
    
                case 2:
                    System.out.println(i + ": " + a + "*" + b + "=");
                    int c = in.nextInt();
                    out.println(a + "*" + b + "=" + c);
                    if (c == counter.multiplication(a, b)) {
                        sum += 10;
                        System.out.println("right!");
                    } else {
                        System.out.println("error!");
                    }
                    break;
                case 3:
                    System.out.println(i + ": " + a + "+" + b + "=");
                    int c1 = in.nextInt();
                    out.println(a + "+" + b + "=" + c1);
                    if (c1 == counter.add(a, b)) {
                        sum += 10;
                        System.out.println("right!");
                    } else {
                        System.out.println("error!");
                    }
                    break;
                case 4:
                    while (a < b) {
                        b = (int) Math.round(Math.random() * 100);
                    }
                                    //因为不能产生运算结果为负数的减法式子,所以a一定要大于b。若a<b,则重新生成b。
                    System.out.println(i + ": " + a + "-" + b + "=");
                    int c2 = in.nextInt();
                    out.println(a + "-" + b + "=" + c2);
                    if (c2 == counter.reduce(a, b)) {
                        sum += 10;
                        System.out.println("right!");
                    } else {
                        System.out.println("error!");
                    }
                    break;
                }
            }
            System.out.println("成绩" + sum);
            out.println("成绩:" + sum);
            out.close();
        }
    }
    package demo;
    
    public class yunsuan<T> {
        private T a;
        private T b;
    
        public yunsuan() {
            a = null;
            b = null;
        }
        public yunsuan(T a, T b) {
            this.a = a;
            this.b = 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;
        }
    }

    实验总结:通过本周实验及课本的内容,学习了泛型的概念与运用,知道了泛型的具体定义、以及它的使用;最后的编程实验是在之前的实验上进行修改、添加本章学习的泛型语句然后实现的,实验不够熟练,还需要多多练习。

  • 相关阅读:
    蓝桥杯 网络寻路
    ny33 蛇形填数
    集合运算 蓝桥杯 set容器
    蓝桥杯 回形取数
    bam/sam格式说明--转载
    samtools一些文档
    Linux批量更改文件后缀-转载
    GATK--使用转载
    Linux下wget下载整个FTP目录(含子目录)--转载
    CRLF line terminators导致shell脚本报错:command not found --转载
  • 原文地址:https://www.cnblogs.com/LZM7343/p/9903372.html
Copyright © 2020-2023  润新知