201871010102-常龙龙《面向对象程序设计(java)》第十一周学习总结

项目

内容

这个作业属于哪个课程

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

这个作业的要求在哪里

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

作业学习目标

     

                                  

              (1) 理解泛型概念;

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

              (3) 了解泛型方法的声明与使用;

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

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

 

第一部分:总结第八章关于泛型程序设计理论知识(25分)

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

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

二、泛型方法
          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. 定义泛型变量的 上界
public class NumberGeneric< T extends Number>

■泛型变量上界的说明

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

●<T extends Bounding Type>表示T应该是绑定类型的子类型。
●一个类型变量或通配符可以有多个限定,限定类型用“&”分割。例如:
           < T extends Comparable & Serlallzable >

2. 定义泛型变量的 上界

■泛型变量下界的说明
        ◆通过使用super关键字可以固定泛型参数的类型为某种类型的超类
        ◆当希望为一个方法的参数限定类型时,通常可以使用下限通配符
public static <T> void sort(T[] a,Comparator<? super T> c)

通配符类型
●通配符
     “?”表明参数类型可以是任何一种类型,通配符-般有以下三种用法:
             1.单独的?,用于表示任何类型。

             2.? extends type, 表示带有上界。

             3.? super type,表示带有下界。

五、泛型程序设计小结
●定义一个泛型类时,在“<>”内定义形式类型参数,例如:“class TestGeneric<K, V>”,其中“K”,“V”不代表值,而是表示类型。
●实例化泛型对象的时候,- 定要在类名后面指定类型参数的值(类型),-共要有两次书写。
        例如:TestGeneric<String, String> t
                                   =new TestGeneric <String, String> ();

●泛型中<T extends Object> , extends并不代表继承,它是类型范围限制。

●泛型类不是协变的。

第二部分:实验部分

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

测试程序1:

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

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

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

代码如下:

1.Pair类:

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; }
}

2.PairTest1类:

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" };
      //向ArrayAlg类的minmax方法中传入一个字符串数组
      //将返回的Pair泛型对象传给Pair泛型变量
      Pair<String> mm = ArrayAlg.minmax(words);
      //通过mm调用它的方法
      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 values, 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];
      }
      //找出字符串数组中的最大最小值后,把两个值作为产生Pair泛型的对象的构造方法参数传入
      //创建对象后并返回
      return new Pair<>(min, max);
   }
}

运行结果如下:

 

 

测试程序2:

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

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

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

代码如下:

1.Pair类

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; }
}

2.PairTest2类

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
         };
      System.out.println("----------------");
      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或空,则为null
   */
   public static <T extends Comparable> Pair<T> minmax(T[] a) 
   //对类型变量进行限定,T限制为实现了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++)
      {
         //实现了Comparable类的的数组可以使用compareTo()方法
         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,结合程序运行结果理解程序;

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

代码如下:

1.Employee类

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.Manager类

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;
   }
}

3.pair类

 

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; }
}

4.PairTest3类

package pair3;

/**
 * @version 1.01 2012-01-26
 * @author Cay Horstmann
 */
public class PairTest3
{
   public static void main(String[] args)
   {
       //创建了两个Manager类对象
      Manager ceo = new Manager("Gus Greedy", 800000, 2003, 12, 15);
      Manager cfo = new Manager("Sid Sneaky", 600000, 2003, 12, 15);
      //将两个Manager类对象作为参数传入到Pair泛型类的构造方法中
      Pair<Manager> buddies = new Pair<Manager>(ceo, cfo);
      //将两个对象作为参数传入静态方法printBuddies,调用两个对象的方法,并打印
      printBuddies(buddies);

      ceo.setBonus(1000000);
      cfo.setBonus(500000);
      
      Manager[] managers = { ceo, cfo };

      Pair<Employee> result = new Pair<Employee>();
      
      //找出managers数组中奖金最小和最大的并且作为参数赋给result的set方法
      minmaxBonus(managers, result); 
      
      //result.getFirst()代表对象
      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)
   {
      //找出a数组中bonus最小的对象和bonus最大的对象
      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泛型的setsetFirst和setSecond方法
      result.setFirst(min);
      result.setSecond(max);
   }

   public static void maxminBonus(Manager[] a, Pair<? super Manager> result)
   {
      minmaxBonus(a, result);
      //调用swapHelper方法将result泛型中的First中保存的最小对象改为最大对象
      PairAlg.swapHelper(result); //OK——swapHelper捕获通配符类型
   }
   // 无法编写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 temp = p.getFirst();
      p.setFirst(p.getSecond());
      p.setSecond(temp);
   }
}

运行结果如下:

 

实验2:结对编程练习(32分)

 

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

push(item);            //如item为null,则不入栈直接返回null。
pop();                 //出栈,如为栈为空,则返回null。
peek();                //获得栈顶元素,如为空,则返回null.
public boolean empty();//如为空返回true
public int size();     //返回栈中元素数量

2定义GeneralStackArrayListGeneralStack要求:

ü 类内使用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程序直接退出。否则,输入整数mnm代表入栈个数,n代表出栈个数。然后声明栈变量stack

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

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

ü 输入Car,打印Car Test。其他操作与IntegerDouble基本一样。只不过最后将栈中元素出栈,并将其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

代码如下:

 1.General类

package work;

interface GeneralStack<T> {
     public T push(T item);
     public T pop();
     public T peek();
     public boolean empty();
     public int size(); 
}

2.ArrayListGeneralStack类

package work;

import java.util.ArrayList;

class ArrayListGeneralStack implements GeneralStack<Object>{
    ArrayList<Object> list=new ArrayList<>();
    
    @Override
    public  Object push(Object item) {
        if(item!=null)
        {
            list.add(item);
            return item;
        }else {
            return null;
        }
    }


    @Override
    public Object pop() {
        if(list.size()==0)
        {
            return null;
        }else {
            return list.remove(list.size()-1);
        } 
        
    }

    @Override
    public Object peek() {
        if(list.size()==0)
        {
            return null;
        }else {
            return list.get(list.size()-1);
        } 
        
    }

    @Override
    public boolean empty() {
        if(list.size()==0)
        {
            return true;
        }else {
            return false;
        }
    }

    @Override
    public int size() {
        return list.size();
    }
     
    public String toString()
    {
        return  list.toString();
    }
}

3.Car类

package work;

public class Car {
    private int id;
    private String name;
    
    public Car(int id, String name) {
        this.id = id;
        this.name = name;
    }
    
    public int getId() {
        return id;
    }
    
    public void setId(int id) {
        this.id = id;
    }
    
    public String getName() {
        return name;
    }
    
    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Car [id=" + id + ", name=" + name + "]";
    }
    
    
}

4.Main类

package work;

import java.util.Scanner;

public class Main {
  
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner in=new Scanner(System.in);
        System.out.println("请输入选项:"+"\n"+"1.quit"+"\n"+"2.Integer"+"\n"+"3.Double"+"\n"+"4.Car");
        System.out.println("-------------------");
        while(true)
        {
            String choice=in.next();
            if(choice.equals("quit")){
                System.out.println("程序终止");
                break;
            }
            else if(choice.equals("Integer"))
            {
                System.out.println("Integer Test");
                int pushStackTimes=in.nextInt();
                int popStackTimes=in.nextInt();
                ArrayListGeneralStack Stack = new ArrayListGeneralStack();
                for(int i=0;i<pushStackTimes;i++)
                {
                    //System.out.print("push:");
                    System.out.println("push:"+Stack.push(in.nextInt()));
                    //Stack.push(in.nextInt());
                }
                for(int j=0;j<popStackTimes;j++)
                {
                    System.out.println("pop:"+Stack.pop());
                }
                System.out.println(Stack.toString());
                
                Integer sum=0;
                int size=Stack.size();
                for(int k=0;k<size;k++)
                {    
                    sum+=(Integer)Stack.pop();
                }
                System.out.println("sum="+sum); 
                
                //打印接口
                System.out.println(Stack.getClass().getInterfaces()[0]);                                 
            }
            else if(choice.equals("Double"))
            {
                System.out.println("Double Test");
                int pushStackTimes=in.nextInt();
                int popStackTimes=in.nextInt();
                ArrayListGeneralStack Stack = new ArrayListGeneralStack();
                for(int i=0;i<pushStackTimes;i++)
                {
                    //System.out.print("push:");
                    System.out.println("push:"+Stack.push(in.nextDouble()));
                    //Stack.push(in.nextDouble());
                }
                for(int j=0;j<popStackTimes;j++)
                {
                    System.out.println("pop:"+Stack.pop());
                }
                System.out.println(Stack.toString());
                
                Double sum=0.0d;
                int size=Stack.size();
                for(int k=0;k<size;k++)
                {    
                    sum+=(Double)Stack.pop();
                }
                System.out.println("sum="+sum); 
                
                //打印接口
                System.out.println(Stack.getClass().getInterfaces()[0]);                
            }
            else if(choice.equals("Car"))
            {
                System.out.println("Car Test");
                int pushStackTimes=in.nextInt();
                int popStackTimes=in.nextInt();
                ArrayListGeneralStack Stack = new ArrayListGeneralStack();
                for(int i=0;i<pushStackTimes;i++)
                {
                    int id=in.nextInt();
                    String name=in.next();
                    Car car=new Car(id,name);
                    //System.out.print("push:");
                    System.out.println("push:"+Stack.push(car));
                    //Stack.push(car);
                }
                for(int j=0;j<popStackTimes;j++)
                {
                    System.out.println("pop:"+Stack.pop());
                }
                System.out.println(Stack.toString());
                
                //打印剩余元素的name
                int size=Stack.size();
                for(int k=0;k<size;k++)
                {    
                    Car car=(Car)Stack.pop();
                    System.out.println(car.getName());
                }
                
                //打印接口
                System.out.println(Stack.getClass().getInterfaces()[0]);                
            }
       }
       in.close();
    }
}

 

5.运行结果如下:

 

 

 

 三、实验总结

这周的知识比较难理解,是一个难点。通过几个测试程序,我基本上理解并且掌握了泛型的定义,以及泛型类、泛型方法以及泛型接口的使用。本次实验的编程练习的难度对我来说有点大,让我觉得我对泛型接口的掌握还不是很到位,最后的代码结果我是理解了网上的博客之后自己写的,虽然到现在对它的领悟还不是很深刻,但我相信通过对成熟代码的理解以及平时不断地编程练习,以后总会在经验中找出掌握它的属于我的独有方法。

 

posted @ 2019-11-08 11:22  北柯  阅读(213)  评论(2编辑  收藏  举报