zoukankan      html  css  js  c++  java
  • 王志成201771010130《面向对象程序设计(java)》第十周学习总结

    理论学习知识

    泛型类的定义:一个泛型类(generic class)就是具有一个或多个类型变量的类,即创建用类型作为参数的类。

    如一个泛型类定义格式如下: class Generics<K,V> 其中的K和V是类中的可变类型参数。

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

     泛型类可以有多个类型变量。例如: public class Pair<t, u> { … }

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

    泛型方法:

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

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

    泛型变量上界的说明

    NumberGeneric类所能处理的泛型变量类型需和Number有继承关系;

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

    <T extends Bounding Type>表示T应该是绑定类型的子类型。

    泛型变量下界的说明

    通过使用super关键字可以固定泛型参数的类型为某种类型或者其超类

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

    通配符:

     “?”符号表明参数的类型可以是任何一种类型,它和参数T的含义是有区别的。T表示一种未知类型,而“?”表示任何一种类型。这种通配符一般有以下三种用法:

    单独的?,用于表示任何类型。

     ? extends type,表示带有上界。

     ? super type,表示带有下界。

    1、实验目的与要求

    (1) 理解泛型概念;

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

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

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

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

    2、实验内容和步骤

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

    测试程序1:

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

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

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

    程序源代码及其注释:

    package pair1;
    
    /**
     * @version 1.00 2004-05-10
     * @author Cay Horstmann
     */
    public class Pair<T> //Pair类引入了一个类型变量T,用尖括号括起来
    {
       private T first;
       private T second;
    //指方法的返回类型以及域和局部变量的类型
       public Pair() { first = null; second = null; }
       public Pair(T first, T second) { this.first = first;  this.second = second; }
    
       public T getFirst() { return first; }
       public T getSecond() { return second; }
    
       public void setFirst(T newValue) { first = newValue; }
       public void setSecond(T newValue) { second = newValue; }
    }
    package pair1;
    
    /**
     * @version 1.01 2012-01-26
     * @author Cay Horstmann
     */
    public class PairTest1
    {
       public static void main(String[] args)
       {
          String[] words = { "Mary", "had", "a", "little", "lamb" };
          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];
             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;
    
    /**
     * @version 1.01 2012-01-26
     * @author Cay Horstmann
     */
    public class PairTest3
    {
       public static void main(String[] args)
       {
          Manager ceo = new Manager("Gus Greedy", 800000, 2003, 12, 15);
          Manager cfo = new Manager("Sid Sneaky", 600000, 2003, 12, 15);
          Pair<Manager> buddies = new Pair<>(ceo, cfo);      
          printBuddies(buddies);
    
          ceo.setBonus(1000000);
          cfo.setBonus(500000);
          Manager[] managers = { ceo, cfo };
    
          Pair<Employee> result = new Pair<>();
          minmaxBonus(managers, result);
          System.out.println("first: " + result.getFirst().getName() 
             + ", second: " + result.getSecond().getName());
          maxminBonus(managers, result);
          System.out.println("first: " + result.getFirst().getName() 
             + ", second: " + result.getSecond().getName());
       }
    
       public static void printBuddies(Pair<? extends Employee> p)
      //? extends type,表示带有上界 
       
       {
          Employee first = p.getFirst();
          Employee second = p.getSecond();
          System.out.println(first.getName() + " and " + second.getName() + " are buddies.");
       }
     //"?"在这儿是通配符,符号表明参数的类型可以是任何一种类型,它和参数T的含义是有区别的
       public static void minmaxBonus(Manager[] a, Pair<? super Manager> result)
       {
          if (a.length == 0) return;
          Manager min = a[0];
          Manager max = a[0];
          for (int i = 1; i < a.length; i++)
          {
             if (min.getBonus() > a[i].getBonus()) min = a[i];
             if (max.getBonus() < a[i].getBonus()) max = a[i];
          }
          result.setFirst(min);
          result.setSecond(max);
       }
    //T表示一种未知类型,而“?”表示任何一种类型
       public static void maxminBonus(Manager[] a, Pair<? super Manager> result)
       {
          minmaxBonus(a, result);
          PairAlg.swapHelper(result); // swapHelper捕获通配符类型
       }
       // 不能写公共静态<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);
       }
    }
    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; }
    }

    程序测试结果如下所示;

    实验2编程练习:

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

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

     实验通过自定义一个类和main类实现。

    main类中主要实现了文件的调用,输出相应实验内容。

    而自定义类则定义了文件中的相关变量和接口的实现。

     困难与问题:主要问题是接口和类的联系和实现比较迷惑。

    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{
        private static ArrayList<person> Personlist;
        public static void main(String[] args) {
            Personlist = 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 ID = linescanner.next();
                    String sex = linescanner.next();
                    String age = linescanner.next();
                    String place =linescanner.nextLine();
                    person Person = new person();
                    Person.setname(name);
                    Person.setID(ID);
                    Person.setsex(sex);
                    int a = Integer.parseInt(age);
                    Person.setage(a);
                    Person.setbirthplace(place);
                    Personlist.add(Person);
    
                }
            } catch (FileNotFoundException e) {
                System.out.println("查找不到信息");
                e.printStackTrace();
            } catch (IOException e) {
                System.out.println("信息读取有误");
                e.printStackTrace();
            }
            boolean isTrue = true;
            while (isTrue) {
                System.out.println("1:按姓名字典序输出人员信息");
                System.out.println("2:查询最大年龄与最小年龄人员信息");
                System.out.println("3:输入你的年龄,查询与你最近人的姓名、身份证号、年龄、性别和出生地;");
                System.out.println("4:查询是否有同乡");
                System.out.println("5:退出");
                int nextInt = scanner.nextInt();
                switch (nextInt) {
                case 1:
                    Collections.sort(Personlist);
                    System.out.println(Personlist.toString());
                    break;
                case 2:
                    
                    int max=0,min=100;int j,k1 = 0,k2=0;
                    for(int i=1;i<Personlist.size();i++)
                    {
                        j=Personlist.get(i).getage();
                       if(j>max)
                       {
                           max=j; 
                           k1=i;
                       }
                       if(j<min)
                       {
                           min=j; 
                           k2=i;
                       }
    
                    }  
                    System.out.println("年龄最大:"+Personlist.get(k1));
                    System.out.println("年龄最小:"+Personlist.get(k2));
                    break;
                case 3:
                    System.out.println("年龄:");
                    int yourage = scanner.nextInt();
                    int near=agenear(yourage);
                    int d=yourage-Personlist.get(near).getage();
                    System.out.println(""+Personlist.get(near));
                    break;
                case 4:
                    System.out.println("你的家乡?");
                    String find = scanner.next();        
                    String place=find.substring(0,3);
                    String place2=find.substring(0,3);
                    for (int i = 0; i <Personlist.size(); i++) 
                    {
                        if(Personlist.get(i).getbirthplace().substring(1,4).equals(place)) 
                            System.out.println(""+Personlist.get(i));
    
                    } 
    
                    break;
                case 5:
               isTrue = false;
               System.out.println("退出程序!");
                    break;
                default:
                    System.out.println("输入有误");
                }
            }
        }
        public static int agenear(int age) {
         
           int j=0,min=53,d=0,k=0;
            for (int i = 0; i < Personlist.size(); i++)
            {
                d=Personlist.get(i).getage()-age;
                if(d<0) d=-d; 
                if (d<min) 
                {
                   min=d;
                   k=i;
                }
    
             }    return k;
            
         }
    
     
    }
    public class person implements Comparable<person> {
    private String name;
    private String ID;
    private int age;
    private String sex;
    private String birthplace;
    
    public String getname() {
    return name;
    }
    public void setname(String name) {
    this.name = name;
    }
    public String getID() {
    return ID;
    }
    public void setID(String ID) {
    this.ID= ID;
    }
    public int getage() {
    
    return age;
    }
    public void setage(int age) {
    this.age= age;
    }
    public String getsex() {
    return sex;
    }
    public void setsex(String sex) {
    this.sex= sex;
    }
    public String getbirthplace() {
    return birthplace;
    }
    public void setbirthplace(String birthplace) {
    this.birthplace= birthplace;
    }
    
    public int compareTo(person o) {
    return this.name.compareTo(o.getname());
    
    }
    
    public String toString() {
    return name+"	"+sex+"	"+age+"	"+ID+"	"+birthplace+"
    ";
    
    }
    
     
    
    }

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

    这个实验主要是通过在主函数中用round() 方法实现随机题目的产生和将题目数字限制在10以内,然后添加异常处理,实现文件的输出。

    困难与问题:对于将结果通过txt文件输出的相关代码有点陌生。

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

     程序源代码:

    package cc;
    public class SF<T> {
           private T a;
           private T b;
           public SF() {
               a = null;
               b = null;
           }
          
           public SF(T a, T b) {
               this.a = a;
               this.b = b;
           }
            public int   SF1(int a,int b)
            {
                return a+b;
            }
            public int  SF2(int a,int b)
            {
                return a-b;
            }
            public int  SF3(int a,int b)
            {
                return a*b;
            }
            public int   SF4(int a,int b)
            {
                if(b!=0)
                return a/b;
                else return 0;
            }
    
            
        }
    package cc;
    import java.io.FileNotFoundException;
    import java.io.PrintWriter;
    import java.util.Scanner;
    
    
    public class Demo {
        public static void main(String[] args) {
    
            Scanner in = new Scanner(System.in);
            SF counter=new SF();
            PrintWriter out = null;
            try {
                out = new PrintWriter("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() * 10);
                int b = (int) Math.round(Math.random() * 10);
                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.SF1(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 d1 = in.nextInt();
                   out.println(a + "-" + b + "=" + d1);
                   if (d1 == counter.SF2(a, b)) {
                       sum += 10;
                       System.out.println("恭喜答案正确");
                   } else {
                       System.out.println("抱歉,答案错误");
                   }
                   break;
               case 2:
                   System.out.println(a + "*" + b + "=");
                   int d2 = in.nextInt();
                   out.println(a + "*" + b + "=" + d2);
                   if (d2 ==counter.SF3(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 d3 = in.nextInt();
                   out.println(a + "/" + b + "=" + d3);
                   if (d3 == counter.SF4(a, b)) {
                       sum += 10;
                       System.out.println("恭喜答案正确");
                   } else {
                       System.out.println("抱歉,答案错误");
                   }
                   break;
    
               }
    
           
    }
            System.out.println("成绩"+sum);
            out.println("成绩:"+sum);
             out.close();
    
             
        }
        }

    总结:这周学习了泛型程序设计,学习了简单的泛型方法,和定义一个简单的泛型类,这周的知识是一项全新的技术,我掌握的并不是很好,对知识的理解还不到位,我会在今后的学习中更加努力,争取理解和消化这项技术。

  • 相关阅读:
    Mybatis学习--spring和Mybatis整合
    MyBatis学习--查询缓存
    MyBatis学习--延迟加载
    MyBatis学习--高级映射
    Mybatis学习--Mapper.xml映射文件
    java文件上传和下载
    【计算机视觉】Object Proposal之BING理解
    【计算机视觉】Object Proposal之BING++
    【计算机视觉】Object Proposal之BING++
    【计算机视觉】Objectness算法(一)---总体理解,整理及总结
  • 原文地址:https://www.cnblogs.com/847118824wang/p/9903839.html
Copyright © 2011-2022 走看看