201871010134- Zhou Yingjie "want to face the object programming (java)" Week 11 learning summary

project

content

"Object-oriented programming (java)"

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

Where this requirement in the job

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

Job learning objectives

  1. Understand the generic concepts;
  2. Master the definition and use of generic classes;
  3. Master the declaration and the use of generic methods;
  4. Grasp the definition and implementation of generic interface;
  5. Learn generic programming, understand their purpose.

Part I: summary of Chapter VIII of theoretical knowledge about generic programming.

1. Generic: What is generic, parameterized types is, when defining the classes, interfaces, methods, indicating the type of object to be processed by the type parameter

2. Generic programming means to write code that can be reused in many different types of objects

3. Define a simple generic class:

  (1) class is a generic class type having one or more variables, i.e., the type used to create a class as a parameter

  (2) In Case of Pair: public class Pair <T>

             {

                                             ......

              }

    Pair class introduces a variable of type T, (<>) enclosed in angle brackets, and follows the class name

  (3) may have a plurality of generic class type variables. For example, the class may be defined Pair, wherein the first domain and a second domain use different types: public class Pair <T, U> {...}

  Return Type field and type of local variables (4) a class definition specifies the type of process variable

  (5) when instantiating a generic object class name must be specified after the value of the parameter type, have a total of two written, for example: TestGeneric <String, String> t = new TestGeneric <String, String> ();

4. The generic method:

  (1) Note that the definition of a generic method, the type of the variable on the back modifier (public static), the return type of the front

  (2) can be defined in the generic method in the general category, it can also be defined in generic classes

  (3) When calling a generic method, into a specific type of angle brackets in front of the method name

The generic interface is defined and implemented:

  (1) the definition: 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. The type of the variable is defined:

  (1) the definition of generic variables upper bound (with the extends)

    <T extends BoundingType> T represents the binding type is a subtype. T and binding type may be class, an interface may be

    A variable type or wildcards may define a plurality of, for example: T extends Comparable & Serializable (of the type defined by '&' separated)

  (2) the lower bound of the defined type variable (using super) example: <? Super T>

7. Restrictions and limitations of the generic class:

  (1) Examples of the basic types can not use the type of parameter

  (2) run-time type query applies only to the original type

  (3) can not be captured can not throw generic class instance

  (4) parameterized type of the array is not legitimate

  (5) type can not be instantiated variables

  (6) generic class type variable static context is invalid

  (7) Note that erased after conflict

8. The generic type of inheritance rules: arrays in Java are covariant, but not the generic class covariant

9. wildcard type :( ?, any type; T, a certain type)

  (1) alone? , Used to mean any type of

  (2)? extends type, represents the upper bound with

  (3)? super type, expressed with a lower bound

10. (1) defining a wildcard type: Pair <extends Employee?>

             Pair<? super Manager>

 (2) indefinite wildcard: Pair (Pair Pair different in that <?>: SetObject can call the original method using any Object Pair class objects) <?>

Part II: Experimental part

Experiment 1: Test Procedure 1

Run the code:

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 new Pair <> (min, max); // where <> is omitted String.
   }
}

pair:

public  class Pair <T> // use of generics.
{
   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;}

}

 

Results are as follows:

 

 

 

Experiment 1: Test Procedure 2

Run the following code:

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 <the LocalDate> mm = ArrayAlg.minmax (Birthdays); // HERE uses generics
      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 new Pair <> (min, max); // <> which is omitted T.
   }
}

pair:

public  class Pair <T> // generics
{
   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; }
}

operation result;

 

 

 

Experiment 1: Test Procedure 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 Fred;
   }

   public void raiseSalary(double byPercent)
   {  
      double raise = salary * byPercent / 100;
      salary += raise;
   }
}

operation result:

 

 

Experiment 2: Pair programming exercises

Run the code:

package tuxing;
import java.util.ArrayList;
import java.util.Scanner;

interface GeneralStack<T>
{
        public T Push (T item);           // The item is null, the stack directly returns null. 
        public T POP ();                  // a stack, such as stack is empty, or null. 
        public T PEEK ();                 // get the top element, such as empty, or null. 
        public  Boolean empty ();          // if blank return to true 
        public  int size ();               // returns the number of elements in the stack 
}
   class ArrayListGeneralStack the 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);;
        }}
    }
}

operation result:

 

Experimental Summary:

        By learning this week, I learned java in generic technologies, including the generic concept; defining and using generic class; declaration and the use of generic methods; the definition and implementation of generic interface; generic programming design, to understand its use and the like. The concept to understand which part is OK, but to write a program lying stunned on the computer next to a word not knock up, do not say it, may in presentation on class seniors I think my train of thought very clear, while the code will be able to get out and back to the dormitory himself in a practice, wow, all hell broke loose, knocking his party to delete two lines, difficult for me, from now on I have to learn every day.

Guess you like

Origin www.cnblogs.com/dlzyj/p/11826224.html