Location>code7788 >text

Java Basics Part of the notes of Mr. Han Shunping's generic types.

Popularity:813 ℃/2024-09-03 17:13:33

553, introduction of generalizations

package .list_;

import .*;
import ;

@SuppressWarnings({"all"})
public class Map_ {
    public static void main(String[] args) {
        //Using traditional methods to solve
        ArrayList arrayList = new ArrayList();
        (new Dog("Wanted", 10)));
        (new Dog("Fat Choy", 1)));
        (new Dog("Yellow", 5)));

        //Suppose our programmer accidentally adds a cat.
        (new Cat("Fortune Cat", 8)));

        for (Object o : arrayList) {
            //Downward transformation Object ->Dog
            Dog dog = (Dog) o;
            (() + ":" + ());
        }
    }
}
class Dog {
    private String name;
    private int age;

    public Dog(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Dog{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
class Cat {
    private String name;
    private int age;

    public Cat(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

 

554, Introduction to generalization

package .list_;

import .*;
import ;

@SuppressWarnings({"all"})
public class Map_ {
    public static void main(String[] args) {
        //1. When we ArrayList<Dog> means that the element stored in the ArrayList collection is of type Dog (more on that later...).
//2. if the compiler finds that the added type does not fulfill the requirements, it will report an error
//3. When traversing, you can take out the Dog type directly instead of Object.
//4. public class ArrayList<E> {} E is called generic, then Dog->E
        ArrayList<Dog> arrayList = new ArrayList<Dog>();
        (new Dog("Wanted", 10)));
        (new Dog("Fat Choy", 1)));
        (new Dog("Yellow", 5)));

        //Suppose our programmer accidentally adds a cat.
//(new Cat("Fortune Cat", 8)).

        ("=== Using generalizations ====");
        for (Dog dog : arrayList) {
            (() + ":" + ());
        }
    }
}
class Dog {
    private String name;
    private int age;

    public Dog(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Dog{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
class Cat {
    private String name;
    private int age;

    public Cat(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

 

 

555, generalized description

 

package .generic_;

public class Generic01 {
    public static void main(String[] args) {
        //Note, in particular, that the specific data type of E is specified when the Person object is defined, i.e., the type of E is determined at compile time.
        Person<String> person = new Person<String>("Han Shunping Education"));
        ();//String
        /*
          You can read the Person class above like this
          class Person<E> {
            String s;//E denotes the data type of s, which is specified when the Person object is defined, i.e., it is determined at compile time what type E is.

            public Person(String s) { //E can also be a parameter type.
                 = s; }
            public Person(String s) { // E can also be a parameter type = s; }

            public String f() {// Return type use E
                return s; }
            }
        }
*/

        Person<Integer> person1 = new Person<Integer>(100);
        ();//Integer
        /*
          You can read the Person class above like this
          class Person<E> {
            Integer s;//E denotes the data type of s, which is specified when the Person object is defined, i.e., it is determined at compile time what type E is.

            public Person(Integer s) { //E can also be a parameter type.
                 = s; }
            public Person(Integer s) { // E can also be a parameter type = s; }

            public Integer f() {// Return type uses E
                return s; }
            }
        }
*/
    }
}

//Generics are used to indicate the type of an attribute of a class by means of an identifier at the time of class declaration.
// Either the type of the return value of a method, or the type of a parameter.
class Person<E> {
    E s;//E denotes the data type of s, which is specified when defining the Person object, i.e., during compilation, it is determined what type E is.

    public Person(E s) {//E can also be a parameter type
        this.s = s;
    }

    public E f() {//The return type uses E
        return s;
    }

    public void show() {
        (());//Display the run type of s
    }
}

 

556, Examples of generalized applications

 

package ;


import .*;

public class WrapperType {
    public static void main(String[] args) {
        //Putting 3 Student Objects into a HashSet Using Generics

        HashSet<Student> students = new HashSet<Student>();
        (new Student("jack", 18));
        (new Student("tom", 28));
        (new Student("mary", 19));

        //(math.) ergodic
        for (Student student : students) {
            (student);
        }

        ("=============");
        //Putting 3 Student Objects into a HashMap using Generics
        /*
           public class HashMap<K,V> {} //generalized declarations
*/
        //K -> String V->Student
        HashMap<String, Student> hm = new HashMap<String, Student>();//Instantiation of Generics
        ("milan", new Student("milan", 38));
        ("smith", new Student("smith", 48));
        ("hsp", new Student("hsp", 28));

        //Iterator EntrySet
        /*
            public Set<<K,V>> entrySet() {
               Set<<K,V>> es;
               return (es = entrySet) == null ? (entrySet = new EntrySet()) : es;
         }
        */
        Set<<String, Student>> entries = ();

        /*
           public final Iterator<<K,V>> iterator() {
              return new EntryIterator();
        }
        */
        Iterator<<String, Student>> iterator = ();
        while (()) {
            <String, Student> next = ();
            (() +"-" + ());
    }



    }
}
class Student {
    private String name;
    private int age;

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

 

557, Details of the use of generalizations

package ;
import .*;

@SuppressWarnings({"all"})
public class WrapperType {
    public static void main(String[] args) {
        //1. To point to the data type of the generalized type is required to be a reference type, can not be a basic data type
        List<Integer> list = new ArrayList<Integer>();//ok
        //List<int> list2 = new ArrayList<int>();//incorrect

//2. Description
//Because E specifies the type of A, the constructor passes in new A().
//After specifying a specific type for a generic, you can pass in that type or its subclasses.
        Pig<A> aPig = new Pig<A>(new A());
        ();
        Pig<A> aPig2 = new Pig<A>(new B());
        ();

        //3. Forms of use of panels
        ArrayList<Integer> list1 = new ArrayList<Integer>();
        List<Integer> list2 = new ArrayList<Integer>();

        //In practice, we tend to abbreviate
//The compiler performs type inference, and it is recommended to use the following syntax
        ArrayList<Integer> list3 = new ArrayList<>();
        List<Integer> list4 = new ArrayList<>();
        ArrayList<Pig> pigs = new ArrayList<>();

        //4. If you write it this way, the generic defaults to Object.
        ArrayList arrayList = new ArrayList();//equal in value ArrayList<Object> arrayList = new ArrayList<>()
    }
}
class A {}
class B extends A{}

class Pig<E> {
    E e;

    public Pig(E e) {
        this.e = e;
    }

    public void f() {
        (());//Type of operation
    }
}

 

559, Generalized Classroom Exercises

 

Create the MyDate class first and then the Employee class.

package ;

import ;

public class MyDate implements Comparable<MyDate> {
    private int year;
    private int month;
    private int day;

    public MyDate(int year, int month, int day) {
        this.year = year;
        this.month = month;
        this.day = day;
    }

    public int getYear() {
        return year;
    }

    public void setYear(int year) {
        this.year = year;
    }

    public int getMonth() {
        return month;
    }

    public void setMonth(int month) {
        this.month = month;
    }

    public int getDay() {
        return day;
    }

    public void setDay(int day) {
        this.day = day;
    }

    @Override
    public String toString() {
        return "MyDate{" +
                "year=" + year +
                ", month=" + month +
                ", day=" + day +
                '}';
    }

    @Override
    public int compareTo(MyDate o) {
        //If name is the same, start comparing from year in birthday
        int yearMinus = year - ();
        if(yearMinus != 0) {
            return yearMinus;
        }
        //If year is the same, compare month
        int monthMinus = month - ();
        if(monthMinus != 0){
            return monthMinus;
        }
        //If month is the same, compare day, day is positive or 0, negative
        return day - ();
    }
}

Employee class

package ;

public class Employee {
    private String name;
    private double sal;
    private MyDate birthday;

    public Employee(String name, double sal, MyDate birthday) {
        this.name = name;
        this.sal = sal;
        this.birthday = birthday;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getSal() {
        return sal;
    }

    public void setSal(double sal) {
        this.sal = sal;
    }

    public MyDate getBirthday() {
        return birthday;
    }

    public void setBirthday(MyDate birthday) {
        this.birthday = birthday;
    }

    @Override
    public String toString() {
        return "\nEmployee{" +
                "name='" + name + '\'' +
                ", sal=" + sal +
                ", birthday=" + birthday +
                '}';
    }
}

main program file

package ;

import ;
import ;

@SuppressWarnings({"all"})
public class WrapperType {
    public static void main(String[] args) {
        ArrayList<Employee> employees = new ArrayList<>();
        (new Employee("tom", 1000, new MyDate(2000, 11, 11)));
        (new Employee("jack", 12000, new MyDate(2001, 12, 12)));
        (new Employee("hsp", 50000, new MyDate(1980, 10, 10)));

        ("employee=" + employees);


        (new Comparator<Employee>() { //Anonymous Internal Classes + Generics
            @Override
            public int compare(Employee emp1, Employee emp2) {
                //Sort by name, and if name is the same, then by birthday. [i.e., customized sorting]
//First validate the incoming parameters to see if they are of type Employee, if not then do not compare them
                if(!(emp1 instanceof Employee && emp2 instanceof Employee)) {
                    ("Incorrect type...");
                    return 0;
                }
                //Compare name, equal to 0 means the names are the same, not equal to 0 means the names are not the same.
//Continue comparing birthdays and years if they are the same.
                int i = ().compareTo(());
                if (i != 0) {
                    return i;//Dissimilarity determines who is ahead and who is behind by the positive and negative values returned
                }
                //The following is a comparison of birthdays, so it's best to do this comparison in the MyDate class, i.e., by wrapping a CompareTo function in the MyDate class.
//After encapsulation, future maintainability and reusability will be greatly enhanced.
                return ().compareTo(());//birthday is of type MyDate
//                //If the names are the same, the comparison starts from the year in birthday
//                int yearMinus = ().getYear() - ().getYear();
//                if(yearMinus != 0) {
//                    return yearMinus;
//                }
//                //If year is the same, compare month
//                int monthMinus = ().getMonth() - ().getMonth();
//                if(monthMinus != 0){
//                    return monthMinus;
//                }
//                //If month is the same, compare day, day is positive or 0, negative
//                return ().getDay() - ().getDay();
            }
        });
        ("==Sorting employees==");
        (employees);
    }
}

 

560, customized generic classes

 

package ;

import ;
import ;
import ;

@SuppressWarnings({"all"})
public class WrapperType {
    public static void main(String[] args) {

        //T=Double, R=String, M=Integer
        Tiger<Double, String, Integer> g = new Tiger<>("john");

        (10.9);//OK, I can find the corresponding set method, the type is also Double.
//        public void setT(T t) {
//             = t;
//        }

        //("yy");//Error. Wrong type.
        ("g=" + g);

        //T=Object R=Object M=Object
        Tiger g2 = new Tiger("john~~");
        ("yy"); //OK, because T=Object "yy"=String is a subclass of Object.
        ("g2=" + g2);

    }
}
//1. Tiger is followed by a generic, so we'll call Tiger a custom generic class.
//2, T, R, M Identifiers for generic types, usually a single uppercase letter
//3. There can be more than one generic identifier.
//4. General members can be generalized (properties, methods).
//5. Arrays that are generalized cannot be initialized.
//6. You can't use class generics in static methods.
class Tiger<T, R, M> {
    String name;
    R r;//Attributes use to generalize
    M m;
    T t;
    //Arrays using generic types cannot be initialized. Because an array cannot determine the type of T in new, it cannot be initialized in memory.
//T[] ts = new T[8];
    T[] ts;

    public Tiger(String name) {
        this.name = name;
    }

    public Tiger(String name, R r, M m, T t) {//Constructors use generalizations
        this.name = name;
        this.r = r;
        this.m = m;
        this.t = t;
    }

    //Because static is related to the class, when the class is loaded, the object has not been created, only when the object is created, we can know what type it is.
//So, if static methods and static properties are generic, the JVM can't complete the initialization of the
//static R r2;
//    public static void m1(M m) {
//
//    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public R getR() {//The return type can be generic
        return r;
    }

    public void setR(R r) {//methods use to generalize
        this.r = r;
    }

    public M getM() {
        return m;
    }

    public void setM(M m) {
        this.m = m;
    }

    public T getT() {
        return t;
    }

    public void setT(T t) {
        this.t = t;
    }

    @Override
    public String toString() {
        return "Tiger{" +
                "name='" + name + '\'' +
                ", r=" + r +
                ", m=" + m +
                ", t=" + t +
                ", ts=" + (ts) +
                '}';
    }
}

 

561, Customizing generic interfaces

 

package ;

import ;
import ;
import ;

@SuppressWarnings({"all"})
public class WrapperType {
    public static void main(String[] args) {

    }
}
/*
 * Notes on the use of generic interfaces
 * 1. Static members of an interface cannot be generic.
 * 2. The type of a generic interface is determined when inheriting or implementing the interface.
 * 3. If no type is specified, the default is Object.
*/
//Inheriting interfaces Specify the type of the generic interface, U=String, R=Double
interface IA extends IUsb<String, Double> {

}
//When we implement the IA interface, because IA inherits the IUsu interface, it specifies U as String and R as Double.
//When implementing the methods of the IUsu interface, use String to automatically replace U, is Double to replace R
class AA implements IA {

    @Override
    public Double get(String s) {
        return 0.0;
    }

    @Override
    public void hi(Double aDouble) {

    }

    @Override
    public void run(Double r1, Double r2, String u1, String u2) {

    }
}
//When implementing an interface, specify the type of the generic interface directly.
//Integer is specified for U Float is specified for R
//So, when we implement the IUsb method, we automatically replace U with Integer and Float with
class BB implements IUsb<Integer, Float> {

    @Override
    public Float get(Integer integer) {
        return 0f;
    }

    @Override
    public void hi(Float aFloat) {

    }

    @Override
    public void run(Float r1, Float r2, Integer u1, Integer u2) {

    }
}
//If no type is specified, the default is Object.
//It is recommended to write it directly as IUsb<Object,Object>.
class CC implements IUsb {//Equivalent to class CC implements IUsb<Object, Object>
    @Override
    public Object get(Object o) {
        return null;
    }

    @Override
    public void hi(Object o) {

    }

    @Override
    public void run(Object r1, Object r2, Object u1, Object u2) {

    } 
}
interface IUsb<U, R> {

    int n = 10;
    //U name;//In interfaces, members are static and cannot be generalized
//You can use interface generics in common methods
    R get(U u);

    void hi(R r);

    void run(R r1, R r2, U u1, U u2);

    //In jdk8, you can use default methods in interfaces, or you can use generics.
    default R method(U u) {
        return null;
    }
}

 

562, Customized generic methods

 

package ;

import ;
import ;
import ;

@SuppressWarnings({"all"})
public class WrapperType {
    public static void main(String[] args) {
        Car car = new Car();
        ("BMW", 100).//When a method is called with parameters passed in, the compiler determines the type.

//test (machinery etc)
//T->String, R-> ArrayList
        Fish<String, ArrayList> fish = new Fish<>();
        (new ArrayList(), 11.3f);
    }
}
//Generic methods can be defined in regular classes or in generic classes.
class Car {//general category
    public void run() {//ordinary method
    }
    //Description Panmethods
//1. <T,R> is the generalized identifier
//2. is provided for use by fly, the parameters of the fly method are also related to the generic type
    public <T, R> void fly(T t, R r) {//generalized method
        (());//String
        (());//Integer
    }
}
class Fish<T, R> {//generic class
    public void run() {//ordinary method
    }
    public<U, M> void eat(U u, M m) {//generalized method

    }
    //clarification
//1. The following hi methods are not generalized methods
//2. it is the hi method that uses the generic type declared by the class.
    public void he(T t) {
    }

    //Generic methods, either class-declared or self-declared.
    public<K> void hello(R r, K k) {
        (());//ArrayList
        (());//Float
    }
}

 

564, generic inheritance and wildcarding

package ;

import .*;

@SuppressWarnings({"all"})
public class WrapperType {
    public static void main(String[] args) {
        Object o = new String("xx");

        //Generics have no inheritance
//List<Object> list = new ArrayList<String>();

        //An example of the use of the following three methods
        List<Object> list1 = new ArrayList<>();
        List<String> list2 = new ArrayList<>();
        List<AA> list3 = new ArrayList<>();
        List<BB> list4 = new ArrayList<>();
        List<CC> list5 = new ArrayList<>();

        //If List<? > c, you can accept any generic type.
        printCollection1(list1);//All five of the following are true
        printCollection1(list2);
        printCollection1(list3);
        printCollection1(list4);
        printCollection1(list5);

        //List<? extends AA> c means upper limit, can accept AA or AA subclasses: i.e., real parameter can only be of type AA,BB,CC.
//        printCollection2(list1);//x
//        printCollection2(list2);//x
        printCollection2(list3);//The following 3 are correct
        printCollection2(list4);
        printCollection2(list5);

        //List<? super AA> c Supports class AA as well as parents of class AA, not limited to direct parents, lower bound on generalization.
        printCollection3(list1);//right
//        printCollection3(list2);//x
        printCollection3(list3);//right
//        printCollection3(list4);//x
//        printCollection3(list5);//x
        
    }

    //Description: List<? > means any generic type is acceptable.
    public static void printCollection1(List<?> c) {
        for (Object object : c) {//wildcard, when taken out, is Object
            (object);
        }
    }

    //extends AA extends AA to indicate the upper limit, can accept AA or AA subclasses, inheritance
    public static void printCollection2(List<? extends AA> c) {
        for (Object object : c) {
            (object);
        }
    }

    //AA: Supports the AA class and its parents. super Subclass class name AA: supports class AA and parents of class AA, not limited to direct parents.
//Establishes a lower bound on generalization
    public static void printCollection3(List<? super AA> c) {
        for (Object object : c) {
            (object);
        }
    }
}
class AA {

}
class BB extends AA {

}
class CC extends BB {

}

 

566, JUnit Usage and Generics Homework

If JUnit doesn't work with Test, open File -- Project Structure -- Modules -- Dependencies -- check JUnit5.8.1 -- click OK and you're done.

 

package .junit_;


import ;

public class JUnit_ {
    public static void main(String[] args) {
        //The traditional way, after the test to add a comment
//new JUnit_().m1();
        //new JUnit_().m2();

    }

    @Test
    public void m1() {
        ("The m1 method was called.");
    }

    @Test
    public void m2() {
        ("The m2 method was called.");
    }
}

There's a green triangle on the left.

 

 

Thought Analysis:

1, define the User class

2, define the Dao class

3, using JUnit test

 

User class

package .junit_;

public class User {
    private int id;
    private int age;
    private String name;

    public User(int id, int age, String name) {
        this.id = id;
        this.age = age;
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "\nUser{" +
                ", age=" + age +
                ", name='" + name + '\'' +
                '}';
    }
}

 

DAO class

package .junit_;

import .*;

public class DAO<T> {//generic class
    private Map<String, T> map = new HashMap<>();

    public T get(String id) { //The return is the User object
        return (id);
    }
    public void update(String id, T entity) {
        (id, entity);
    }
    //Return the T object as an ArrayList, traverse the map, encapsulate all values of the map (T entity), and return them as an ArrayList.
    public List<T> list() {
        //Creating an ArrayList
        List<T> list = new ArrayList<>();

        //Iterate over the map
        Set<String> keySet = ();
        for (String key : keySet) {
            (get(key));//Call the methods of the DAO class public T get(String id){}
        }
        return list;
    }

    public void delete(String id) {
        (id);
    }

    public void save(String id, T entity) {
        (id, entity);
    }
}

 

test category

package .junit_;


import ;

import ;

public class JUnit_ {
    public static void main(String[] args) {

    }
    @Test
    public void testList() {
        //Here we assign T a type of User
        DAO<User> dao = new DAO<>();
        ("01", new User(1,10,"jack"));
        ("02", new User(2,18,"king"));
        ("03", new User(3,38,"smith"));

        List<User> list = ();
        ("list=" + list);

        ("03", new User(3, 58, "milan"));
        ("01");//removing
        ("===Modified===");
        list = ();
        ("list=" + list);

        ("id=03" + ("03"));

    }
}