zoukankan      html  css  js  c++  java
  • 201871010134周英杰《面想对象程序设计(java)》第十一周学习总结

    项目

    内容

    《面向对象程序设计(java)》

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

    这个作业的要求在哪里

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

    作业学习目标

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

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

    1.泛型:何为泛型,就是参数化类型,在定义类、接口、方法时通过类型参数指示将要处理的对象类型

    2.泛型程序设计意味着编写的代码可以被许多不同类型的对象所重用

    3.定义简单泛型类:

      (1)一个泛型类就是具有一个或多个类型变量的类,即创建用类型作为参数的类

      (2)以Pair类为例:public class Pair<T>

                 {

                                                 ......

                  }

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

      (3)泛型类可以有多个类型变量。例如,可以定义Pair类,其中第一个域和第二个域使用不同的类型:public class Pair<T,U> { ... }

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

      (5)实例化泛型对象时,一定要在类名后面指定类型参数的值,一共要有两次书写,例如:TestGeneric<String,String> t=new TestGeneric<String,String>();

    4.泛型方法:

      (1)定义泛型方法时注意,类型变量放在修饰符(public static)的后面,返回类型的前面

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

      (3)当调用一个泛型方法时,在方法名前的尖括号中放入具体的类型

    5.泛型接口的定义与实现:

      (1)定义:public interface IPool<T>

                               {

             T get();

                int add(T t);

                               }

      (2)实现:public class GenericPool<T> implements IPool<T> { ... }

             public class GenericPool implements IPool<Account> { ... }

    6.类型变量的限定:

      (1)定义泛型变量的上界(用extends)

        <T extends BoundingType>表示T是绑定类型的子类型。T和绑定类型可以是类,也可以是接口

        一个类型变量或通配符可以有多个限定,例如:T extends Comparable & Serializable(限定类型用“&”分隔)

      (2)定义泛型变量的下界(用super)     例如:<? super T>

    7.泛型类的约束与局限:

      (1)不能用基本类型实例化类型参数

      (2)运行时类型查询只适用于原始类型

      (3)不能抛出也不能捕获泛型类实例

      (4)参数化类型的数组不合法

      (5)不能实例化类型变量

      (6)泛型类的静态上下文中类型变量无效

      (7)注意擦除后的冲突

    8.泛型类型的继承规则:Java中的数组是协变的,但泛型类不是协变的

    9.通配符类型:(?,任何类型;T,某一种类型)

      (1)单独的?,用于表示任何类型

      (2)?extends type,表示带有上界

      (3)? super type,表示带有下界

    10.(1)通配符的类型限定: Pair<? extends Employee>

                 Pair<? super Manager>

     (2)无限定通配符:Pair<?>(Pair<?>与Pair的不同在于:可以用任意Object对象调用原始的Pair类的setObject方法)

    第二部分:实验部分

    实验1:测试程序1

    运行代码:

    PairTest1:

    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 values, or null if a is null or empty
        */
       public static Pair<String> minmax(String[] a)//改主类是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);//该处<>中省略的是String。
       }
    }

    pair:

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

    }

     

    运行结果如下:

    实验1:测试程序2

    运行代码如下:

    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 values, 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);//<>里面省略了T。
       }
    }

    pair:

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

    运行结果;

    实验1:测试程序1

    PairTest3:

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

    pair:

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

    Manager:

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

    Employee:

    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:结对编程练习

    运行代码:

    package tuxing;
    import java.util.ArrayList;
    import java.util.Scanner;
    
    interface GeneralStack<T>
    {
            public T push(T item);          //如item为null,则不入栈直接返回null。
            public T pop();                 //出栈,如为栈为空,则返回null。
            public T peek();                //获得栈顶元素,如为空,则返回null.
            public boolean empty();         //如为空返回true
            public int size();              //返回栈中元素数量
    }
      class ArrayListGeneralStack implements GeneralStack
     {
         
         ArrayList list = new ArrayList();
         public String toString()
         {
             return list.toString();
         }
        @Override
        public Object push(Object item) {
             if (list.add(item)){
                    return item;
                }else {
                    return false;
                }
            }
    
        @Override
        public Object pop() {
             if (list.size()==0){
                return null;}
             return list.remove(list.size()-1);
        }
    
        @Override
        public Object peek() {
            if(list.size()!=0)
                 return list.get(list.size()-1);
            return null;
        }
    
        @Override
        public boolean empty() {
            if(list.size()==0)
                return true;
            return false;
        }
    
        @Override
        public int size() {
            // TODO Auto-generated method stub
            return list.size();
        }
         
     }
      
    class Car
    {
        private int id;
        private String name;
        
         @Override
            public String toString() {
                return "Car [" + "id=" + id +", name=" + getName()  +']';
            }
         
            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;
            }
            public Car(int id, String name) {
                this.id = id;
                this.setName(name);
            }
    }
    public class Main {
        
        public static void main(String[] args) {
            Scanner in = new Scanner(System.in);
            while(true){
            String c = in.nextLine();
            if(c.equals("Integer"))
            {
                System.out.println("Integer Test");
                int m=in.nextInt();
                int n=in.nextInt();
                ArrayListGeneralStack array = new ArrayListGeneralStack();
                for(int i=0;i<m;i++)
                {
                    System.out.println("push:"+array.push(in.nextInt()));
                }
                for(int i=0;i<n;i++)
                {
                System.out.println("pop:"+array.pop());
                }
                System.out.println(array.toString());
                int sum=0;
                int size=array.size();
                for(int i=0;i<size;i++)
                {
                    sum+=(int)array.pop();
                }
                System.out.println("sum="+sum);
                System.out.println("interface GeneralStack");
            }
            else if(c.equals("Double"))
            {
                System.out.println("Double Test");
                int m = in.nextInt();
                int n = in.nextInt();
                ArrayListGeneralStack array = new ArrayListGeneralStack();
                for (int i=0;i<m;i++)
                {
                    System.out.println("push:"+array.push(in.nextDouble()));
                }
                for(int i=0;i<n;i++)
                {
                    System.out.println("pop:"+array.pop());
                }
                System.out.println(array.toString());
                double sum=0;
                int size=array.size();
                for(int i =0;i<size;i++)
                {
                    sum+=(double)array.pop();
                }
                System.out.println("sum="+sum);
                System.out.println("interface GeneralStack");
            }
            else if(c.equals("Car"))
            {
                System.out.println("Cat Test");
                int m=in.nextInt();
                int n=in.nextInt();
                ArrayListGeneralStack array = new ArrayListGeneralStack();
                for(int i=0;i<m;i++)
                {
                    int id = in.nextInt();
                    String name = in.next();
                    Car car = new Car(id, name);
                    System.out.println("push"+array.push(car));
                }
                for(int i =0;i<n;i++)
                {
                    System.out.println("pop"+array.pop());
                }
                System.out.println(array.toString());
                int size=array.size();
                for(int i=0;i<size;i++)
                {
                    Car car=(Car) array.pop();
                    System.out.println(car.getName());
                }
                
                System.out.println("interface GeneralStack");
            }
            else if (c.equals("quit")){
              System.exit(0);;
            }}
        }
    }

    运行结果:

    实验总结:

            通过本周的学习,我了解到了java中的泛型技术,其中包括了泛型概念;泛型类的定义与使用;泛型方法的声明与使用;泛型接口的定义与实现;泛型程序设计,理解其用途等。其中的概念部分理解起来还算可以,但是一到编写程序,愣是趴在电脑旁一个字都敲不上去,说不会吧,可就在上节课学长的演示下我觉的我的思路很清晰,一会儿就能把代码搞出来,回到宿舍自己一搞,哇,全乱套了,敲一行删两行,我太难了,从现在开始我一定要好好学习天天向上。

  • 相关阅读:
    asp.net core 发布centos 7 遇到的坑
    模拟EF CodeFist 实现自己的ORM
    EF+Redis(StackExchange.Redis)实现分布式锁,自测可行
    Sqlite 梳理
    mina.net 梳理
    C# 读取Execl和Access数据库
    MVC4.0网站发布和部署到IIS7.0上的方法
    看懂SqlServer查询计划
    C#数据表加锁解锁
    『C#基础』数据库死锁笔记
  • 原文地址:https://www.cnblogs.com/dlzyj/p/11826224.html
Copyright © 2011-2022 走看看