javaSE___ Collection system 06___ generic paradigm

1, Generic overview and basic usage

  • A: Overview of generics: java generics is essentially a parameterized type, that is, the operated data type is specified as a parameter (type parameter). This parameter type can be used in the creation of classes, interfaces and methods, which are called generic classes, generic interfaces and generic methods respectively.

  • B: Generic benefits

    • Improve security (convert runtime errors to compile time)
    • Save the trouble of forced transfer
  • C: Generic basic usage

    • < > must be a reference data type
  • D: Generic usage considerations

    • The previous and subsequent generics must be consistent, or the following generics can be omitted without writing (diamond generics, a new feature of 1.7)

1. Let's take an example to see the benefits of generics:

We have a Person entity class with attributes of name and age.

public static void main(String[] args) {
		ArrayList<Person> list = new ArrayList<Person>();
		list.add(new Person("Zhang San", 23));
		list.add(new Person("Li Si", 24));
		
		Iterator<Person> it = list.iterator();
		while(it.hasNext()) {
			//The next method can only be called once. If called many times, the pointer will be moved back many times
			Person p = it.next();			
			System.out.println(p.getName() + "..." + p.getAge());	//Output Zhang San 23, Li Si 24
		}
}

2. Let's take an example to see that the generics before and after must be consistent:

public static void main(String[] args) {
		//ArrayList<Object> list = new ArrayList<Person>(); 	// The generic type of the collection should ensure that the data types before and after are consistent
		//ArrayList<Object> list = new ArrayList<>(); 		// The new feature of version 1.7, diamond generics, is written in the front and can not be written later
		ArrayList<Object> list = new ArrayList<>();			//It is better not to define a generic type as an Object, which is meaningless
		list.add("aaa");
		list.add(true);
	}

2, ArrayList stores strings and custom objects and traverses the generic version

1. Store string traversal

/**
	 * * A:Case demonstration
	 * ArrayList Store the string and traverse the generic version
*/
public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>();			//Create collection object
        list.add("a");
        list.add("b");
        list.add("c");
        list.add("d");

        Iterator<String> it = list.iterator();
        while(it.hasNext()) {
            System.out.println(it.next());		//Output a,b,c,d
        }
    }

2. Store custom object traversal

public static void main(String[] args) {
		ArrayList<Person> list = new ArrayList<>();
		list.add(new Person("Zhang San", 23));
		list.add(new Person("Li Si", 24));
		list.add(new Person("Wang Wu", 25));
		list.add(new Person("Zhao Liu", 26));
		
		Iterator<Person> it = list.iterator();
		while(it.hasNext()) {
			Person p = it.next();							//Record each element in the collection with Person
			System.out.println(p.getName() + "..." + p.getAge());		//The output is the four person s added above
		}
	}

3, Overview and use of generic classes

  • A: Overview of generic classes
    • Define generics on classes
  • B: Define format
    • public class class name < generic type 1,... >
  • C: Precautions
    • Generic type must be a reference type

Create a Person class

public class Person {
	private String name;
	private int age;
	public Person() {
		super();
	}
	public Person(String name, int age) {
		super();
		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 "Person [name=" + name + ", age=" + age + "]";
	}
}

Create a Student class and inherit Person

public class Student extends Person {
	public Student() {
	}
	public Student(String name, int age) {
		super(name, age);
	}
}

Next, the main play is to create a generic class

// In general, we require that generics be one character, uppercase, and lowercase if other letters are given
// T represents the type, E represents the element, which has no meaning. It's OK to have a Q
// When is this Q worth it? When we use the Tool class Tool to create objects, we specify generics and what generics are, so this Q is what.
public class Tool<Q> {		
	private Q q;

	public Q getObj() {
		return q;
	}

	public void setObj(Q q) {
		this.q = q;
	}
}

Let's test it

public static void main(String[] args) {
        Tool<Student> t = new Tool<>();		//Create a Tool class object Tool, and specify that the generic type is Student
		t.setObj(new Student("Zhang San",23));	
    }

4, Overview and use of generic methods

  • A: Overview of generic methods
    • Define generics on Methods
  • B: Define format
    • Public < generic type > return type method name (generic type variable name)

1. The first way:

Next, we give an overview and use of the generic class above. We add a generic method to the Tool class.

public void show(Q q) {				
		System.out.println(q);				
	}

Let's test it

public static void main(String[] args) {
		Tool<String> t = new Tool<>();
		t.show("abc");		//Output abc
	}

2. The second way:

We will add another generic method in the Tool class, which is inconsistent with the generic type of the class

public<T> void showone(T t) {		//Method generics are best consistent with class generics
		System.out.println(t);		//If it is inconsistent, you need to declare the generic type on the method, which means that the method has its own generic type
	}

Let's test it

public static void main(String[] args) {
		Tool<String> t = new Tool<>();
		t.show(true);		//Output true
	}

3. The third way:

We add another static generic method to the Tool class

//Static methods must declare their own generics. If static generic methods do not declare their own generics, they will report an error
/*The reason for the error is that it is static. Static methods are loaded with the loading of classes. When our classes are loaded,
  The object may not have been created. If the object is not created, W will have no value, and an error will be reported. 	
*/
public static<W> void print(W w) {		//Static methods must declare their own generics
		System.out.println(w);
}

Let's test it

public static void main(String[] args) {
		Tool<String> t = new Tool<>();
		t.show("1111");		//Output 1111
	}

5, Overview and use of generic interfaces

  • A: Generic Interface Overview
    • Define generics on interfaces
  • B: Define format
    • public interface interface name < generic type >

1. The first method is to specify a generic type, which is recommended:

Look directly at the code

/**
	test
*/
public class StringBuffer_01 {
    public static void main(String[] args) {
        Demo d = new Demo();
        d.show("asdasdasd");        //Output asdasd
    }
}

/**
 * Define a generic interface
 * @param <T>
 */
interface Inter<T> {
    public void show(T t);
}

/**
 * Implementing generic interfaces
 */
class Demo implements Inter<String> {
    public void show(String t) {
        System.out.println(t);
    }
}

2. The second way is not to specify generics:

Look directly at the code

/**
	test
*/
public class StringBuffer_01 {
    public static void main(String[] args) {
        Demo d = new Demo();
        d.show("asdasdasd");        //Output asdasd
    }
}

/**
 * Define a generic interface
 * @param <T>
 */
interface Inter<T> {                //This is recommended
    public void show(T t);
}

/**
 * Implementing generic interfaces
 */
class Demo<T> implements Inter<T> {			//There is no need to add generics to your classes when implementing interfaces
    public void show(T t) {
        System.out.println(t);
    }
}

6, Generic advanced wildcards

  • A: Generic wildcard <? >
    • Any type, if not specified, is Object and any Java class
  • B:? extends E
    • Downward qualification, E and its subclasses
  • C:? super E
    • Upward qualification, E and its parent class

A. B example:

public static void main(String[] args) {
		
		//A: Generic wildcard <? >
		//List<?>  list = new ArrayList<Integer>(); 	  // When the generic type on the right is uncertain, the left can be specified as?
		
		//B:? extends E
		ArrayList<Person> list1 = new ArrayList<>();
		list1.add(new Person("Zhang San", 23));
		list1.add(new Person("Li Si", 24));
		list1.add(new Person("Wang Wu", 25));
		
		ArrayList<Student> list2 = new ArrayList<>();
		list2.add(new Student("Zhao Liu", 26));
		list2.add(new Student("Zhou Qi", 27));
		
		list1.addAll(list2);
		System.out.println(list1);
		
	}

----

It's not easy to create. If you feel good, you can easily praise, pay attention to and collect (* ~). Thank you~~

Keywords: Java Back-end set

Added by wee493 on Tue, 11 Jan 2022 21:45:47 +0200