zoukankan      html  css  js  c++  java
  • 201871010109胡欢欢《面向对象程序设计(java)》第十一周学习总结 201871010109

    项目

    内容

    这个作业属于哪个课程

    https://www.cnblogs.com/nwnu-daizh/

    这个作业的要求在哪里

    https://www.cnblogs.com/nwnu-daizh/p/11815810.html

    作业学习目标

    1. 理解泛型概念;
    2. 掌握泛型类的定义与使用;
    3. 掌握泛型方法的声明与使用;
    4. 掌握泛型接口的定义与实现;
    5. 了解泛型程序设计,理解其用途。

    第一部分:第八章理论知识总结(25分)

    一.为什么要使用泛型程序设计

    1.使用泛型机制编写的程序代码要比那些杂乱的使用object变量,然后再进行强制类型转换的代码具有更好的安全性和可读性
    2.泛型程序设计意味着编写的代码可以被很多不同类型的对象所重用。
       在Java中增加泛型类之前,泛型程序设计是用继承实现的。但是有两个问题:当获取一个值时必须进行强制类型转换,,这里没有错误检查,可以向数组列表中添加任何类的对象
    3.类型参数的魅力在于:使得程序具有更好的可读性和安全性

    二.什么是泛型程序设计

    • JDK5.0中增加的泛型类型,是java语言中类型安全的一次重要改进。
    • 泛型:也称参数化类型,就是在定义类,接口和方法时,通过类型参数指示将要处理的对象类型。
    • 泛型程序设计:编写代码可以被很多不同类型的对象所重用

    三.定义简单泛型类
          。 类型变量使用大写形式,且比较短,这是很常见的。在Java库中,使用变量E来表示集合的元素类型,K和V来表示关键字与值的类型。T表示“任意类型”

          。泛型:具有类型参数(类型变量),可以用其他具体的类来替代此参数,从而扩大方法的实用范围以及提高程序的安全性。 
    泛型类:具有一个或多个类型变量的类,用具体的类替换类型变量即为实例化泛型类。

               public class Pair<T,U>

                   {        ...               //两个以上类型变量用,隔开

                                    }

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

    五、泛型接口的定义
    ●定义
    public interface IPool <T>{
               T get();
               int add(T t); 
    }
    ●实现
    public class GenericPool <T> implements IPool<T>
    {

    .....

    }
    public class GenericPool implements IPool< Account>

    {

    .....

    }

    第二部分:实验部分

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

    测试程序1:(6分)

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

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

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

    代码如下:

    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);//words是通过类名调用,依赖于ArrayAlg类
          System.out.println("min = " + mm.getFirst());
          System.out.println("max = " + mm.getSecond());
       }
    }
     
    class ArrayAlg
    {
     /**
             * 获取字符串数组的最小值和最大值。.
             * @param a an array of strings
             * @return 一个具有最小值和最大值的对,如果A为空或空,则为null
         */
       public static Pair<String> minmax(String[] a)//Pair<String>实例化泛型类型
       {
          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);//返回新的泛型类
       }
    }

    PairTest类

    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);//words是通过类名调用,依赖于ArrayAlg类
          System.out.println("min = " + mm.getFirst());
          System.out.println("max = " + mm.getSecond());
       }
    }
     
    class ArrayAlg
    {
     /**
             * 获取字符串数组的最小值和最大值。.
             * @param a an array of strings
             * @return 一个具有最小值和最大值的对,如果A为空或空,则为null
         */
       public static Pair<String> minmax(String[] a)//Pair<String>实例化泛型类型
       {
          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,结合程序运行结果理解程序;

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

    了解泛型方法、泛型变量限定的定义及用途。

    PairTest2.java:

    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
    {
        /**
              获取T类型对象数组的最小值和最大值。
    @param  T类型的对象数组
    @return 一个具有最小值和最大值的对,如果A为空或空,则为null
    */
       public static <T extends Comparable> Pair<T> minmax(T[] a) //泛型方法minmax
       {
          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,结合程序运行结果理解程序;

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

    PairTest3.java:

    package pair3;
     
    /**
     * @version 1.01 2012-01-26
     * @author Cay Horstmann
     */
    public class PairTest3
    {
       public static void main(String[] args)
       {
          var ceo = new Manager("Gus Greedy", 800000, 2003, 12, 15);
          var cfo = new Manager("Sid Sneaky", 600000, 2003, 12, 15);
          var buddies = new Pair<Manager>(ceo, cfo);     
          printBuddies(buddies);
     
          ceo.setBonus(1000000);
          cfo.setBonus(500000);
          Manager[] managers = { ceo, cfo };
     
          var result = new Pair<Employee>();
          minmaxBonus(managers, result);
          System.out.println("first: " + result.getFirst().getName()
             + ", second: " + result.getSecond().getName());
          maxminBonus(managers, result);
          System.out.println("first: " + result.getFirst().getName()
             + ", second: " + result.getSecond().getName());
       }
     
       public static void printBuddies(Pair<? extends Employee> p)//通配符类型可将子类传递给父类
       {
          Employee 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);
       }
    }
    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; }
    }
    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;
     
    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;
       }
    }

    实验2:结对编程练习

    实验2:结对编程练习,将程序提交到PTA2019面向对象程序设计基础知识测试题(2))

    1编写一个泛型接口GeneralStack,要求类中方法对任何引用类型数据都适用。GeneralStack接口中方法如下:

    push(item);            //如item为null,则不入栈直接返回null。

    pop();                 //出栈,如为栈为空,则返回null。

    peek();                //获得栈顶元素,如为空,则返回null.

    public boolean empty();//如为空返回true

    public int size();     //返回栈中元素数量

    2)定义GeneralStack的子类ArrayListGeneralStack要求:

    ü  类内使用ArrayList对象存储堆栈数据,名为list;

    ü  方法: public String toString()//代码为return list.toString();

    ü  代码中不要出现类型不安全的强制转换。

    3)定义Car类,类的属性有:

    private int id;

    private String name;

    方法:Eclipse自动生成setter/getter,toString方法。

    4main方法要求

    ü  输入选项,有quit, Integer, Double, Car 4个选项。如果输入quit,程序直接退出。否则,输入整数m与n。m代表入栈个数,n代表出栈个数。然后声明栈变量stack。

    ü  输入Integer,打印Integer Test。建立可以存放Integer类型的ArrayListGeneralStack。入栈m次,出栈n次。打印栈的toString方法。最后将栈中剩余元素出栈并累加输出。

    ü  输入Double ,打印Double Test。剩下的与输入Integer一样。

    ü  输入Car,打印Car Test。其他操作与Integer、Double基本一样。只不过最后将栈中元素出栈,并将其name依次输出。

    特别注意:如果栈为空,继续出栈,返回null

    输入样例

    Integer

    5

    2

    1 2 3 4 5

    Double

    5

    3

    1.1 2.0 4.9 5.7 7.2

    Car

    3

    2

    1 Ford

    2 Cherry

    3 BYD

    quit

    输出样例

     

    Integer Test

    push:1

    push:2

    push:3

    push:4

    push:5

    pop:5

    pop:4

    [1, 2, 3]

    sum=6

    interface GeneralStack

    Double Test

    push:1.1

    push:2.0

    push:4.9

    push:5.7

    push:7.2

    pop:7.2

    pop:5.7

    pop:4.9

    [1.1, 2.0]

    sum=3.1

    interface GeneralStack

    Car Test

    push:Car [id=1, name=Ford]

    push:Car [id=2, name=Cherry]

    push:Car [id=3, name=BYD]

    pop:Car [id=3, name=BYD]

    pop:Car [id=2, name=Cherry]

    [Car [id=1, name=Ford]]

    Ford

    interface GeneralStack

    结对编程实验代码:

     
    package week111;
    
    public interface GeneralStack<T> {
       public T push(T item);//判断栈是否为空
       public T pop();//出栈,如果栈为空则返回null
       public T peek();//获得栈顶元素,如果为空,则返回null
       public boolean empty();//如为空返回true
       public int size();     //返回栈中元素数量
    }
     
     
    package week111;
    
    public class Car {
            private int id;
            private String name;
            
            public String toString() {
                return "Car ["+"id="+id+",name="+name+']';
            }
            
            public int getId() {
                return id;
            }
            public void setId()
            {
                this.id=id;
            }
            public String getName(){
                return name;
            }
            
            public void setName(String name) {
                this.name=name;
            }
            public Car(int id,String name)
            {
                this.id=id;
                this.name=name;
            }
        }
     
     
    package week111;
    
    import java.util.ArrayList;
    
    public class ArrayListGeneralStack<E> implements GeneralStack {
        ArrayList  list=new ArrayList<E>();
        public String toString() {
            return list.toString();
        }
        @Override
        public Object push(Object item) {
            // TODO Auto-generated method stub
            if(list.add(item)) {
                return item;
            }
            else
            {
                return false;
            }
        }
        @Override
        public Object pop() {
            // TODO Auto-generated method stub
            if(list.size()==0) {
                return null;
            }
            return list.remove(list.size()-1);
        }
    
        @Override
        public Object peek() {
            // TODO Auto-generated method stub
            return list.get(list.size()-1);
        }
    
        @Override
        public boolean empty() {
            // TODO Auto-generated method stub
            if(list.size()==0) {
            return true;
        }else {
            return false;
        }
        }
    
        @Override
        public int size() {
            // TODO Auto-generated method stub
            return list.size();
        }
    
    }
     
     
    package week111;
    
    import java.util.Scanner;
    
    public class Main {
       public static void main(String[] args) {
           Scanner sc=new Scanner(System.in);
           while(true) {
               String s=sc.next();
               if(s.equals("Double")) {
                   System.out.println("Double Test");
                   int count=sc.nextInt();
                   int pop_time=sc.nextInt();
                 ArrayListGeneralStack  generalStack=new ArrayListGeneralStack();
                   for(int i=0;i<count;i++) {
                       System.out.println("push:"+generalStack.push(sc.nextDouble()));
                   }
                   for(int j=0;j<pop_time;j++)
                   {
                       System.out.println("pop:"+generalStack.pop());
                   }
                   System.out.println(generalStack.toString());
                   double sum=0;
                   int size=generalStack.size();
                   for(int i=0;i<size;i++) {
                       sum+=(double)generalStack.pop();
                   }
                   System.out.println("sum="+sum);
                   System.out.println("interface GeneralStack");
               }else if(s.equals("Integer")) {
                   System.out.println("Integer Test");
                   int count=sc.nextInt();
                   int pop_time=sc.nextInt();
                   ArrayListGeneralStack generalStack=new ArrayListGeneralStack();
                       for(int i=0;i<count;i++)
                       {
                           System.out.println("push:"+generalStack.push(sc.nextInt()));
                       }
                       for(int j=0;j<pop_time;j++)
                       {
                           System.out.println("pop:"+generalStack.pop());
                       }
                       System.out.println(generalStack.toString());
                       int sum=0;
                       int size=generalStack.size();
                       for(int i=0;i<size;i++) {
                           sum+=(int)generalStack.pop();
                       }
                       System.out.println("sum="+sum);
                       System.out.println("interface GeneralStack");
               }else if (s.equals("Car")){
                            System.out.println("Car Test");
                            int count=sc.nextInt();
                            int pop_time=sc.nextInt();
                            ArrayListGeneralStack     generalStack = new ArrayListGeneralStack();
                            for (int i=0;i<count;i++){
                                int id=sc.nextInt();
                                String name=sc.next();
                                Car car = new Car(id,name);
                                System.out.println("push:"+generalStack.push(car));
                            }
                            for (int i=0;i<pop_time;i++){
                                System.out.println("pop:"+generalStack.pop());
                            }
                            System.out.println(generalStack.toString());
                            if (generalStack.size()>0){
                                int size=generalStack.size();
                                for (int i=0;i<size;i++){
                                    Car car=(Car) generalStack.pop();
                                    System.out.println(car.getName());
                                }
                            }
                            System.out.println("interface GeneralStack");
                        }else if (s.equals("quit")){
                            break;
                        }
                    } 
            }
    }
     

    实验总结:

    1 泛型的概念定义:

             i.引入了参数化类型(Parameterized Type)的概念,改造了所有的Java集合,使之都实现泛型,允许程序在创建集合时就可以指定集合元素的类型,比如List<String>就表名这是一个只能存放String类型的List;

             ii. 泛型(Generic):就是指参数化类型,上面的List<String>就是参数化类型,因此就是泛型,而String就是该List<String>泛型的类型参数;

        3) 泛型的好处:

             i. 使集合可以记住元素类型,即取出元素的时候无需进行强制类型转化了,可以直接用原类型的引用接收;

             ii. 一旦指定了性参数那么集合中元素的类型就确定了,不能添加其他类型的元素,否则会直接编译保存,这就可以避免了“不小心放入其他类型元素”的可能;

     2,通配符

    1.)在实例化对象的时候,不确定泛型参数的具体类型时,可以使用通配符进行对象定义。

    2)<? extends Object>代表上边界限定通配符

    3) <? super Object>代表下边界限定通配符。

    实验心得:

    通过本周的学习,我掌握了泛型类、泛型方法及泛型接口的定义及泛型变量的限定,通过上课时老师的讲解,我对知识点的理解得以加深。

    在本周结对编程训练时,我发现自己对于Java程序的编写还不是很熟练,今后我会加大训练量,争取做的更好。

     
     
  • 相关阅读:
    查看某个存储过程
    qemu-libvirt-kvm三者之间的关系
    gitlab安装
    jenkins安装
    数据库迁移(分享十一续集)
    数据库迁移(分享十一续集)
    数据库迁移(分享十一续集)
    数据库迁移(分享十一)
    云上迁移(分享十)
    阿里云迁移(分享九)
  • 原文地址:https://www.cnblogs.com/1763088787h/p/11838637.html
Copyright © 2011-2022 走看看