Summary:This section describes several usage methods of generics.
Definitions of simple classes and interfaces:
public class Pair<T> {private T first;public Pair(T first) {this.first = first;}public T getFirst() {return first;}}
public interface ICache<K, V> {public V put(K key, V value);public V get(K key);}
PS: type variables are in uppercase and are short. In the Java library, variable e Represents the elements of the Set, and K and v represent the types of table keywords and values respectively. T indicates "any type ".
Generic method:
public class Test {public static <T> T getObj(T a) {return a;}public static void main(String args[]) {String str = getObj("a");Student student = getObj(new Student());}}class Student {}
This is certainly not the case in the example of the actual code, but it represents an obvious advantage of the generic method: t can be of any type ".
Inheritance of type variables:
public class ArrayTest {public static <T extends Comparable> T min(T[] a) {if (a == null || a.length == 0)return null;T smallest = a[0];for (int i = 1; i < a.length; i++) {if (smallest.compareTo(a[i]) > 0) {smallest = a[i];}}return smallest;}}
Here, T must ensure that the compareto method is available. Therefore, use <t extends comparable> to limit T to the comparable interface.
PS: <t extends bounding type> indicates that T should be the word type (subtype) of the binding type, and t and the binding type can be classes or interfaces. I think it can be understood that the keyword extends here is not the extends keyword in inheritance, and it is only a code for the compiler. The designer selects the keyword extends because it is closer to the concept of subclass.
References:
Java core technology volume 1
Thomescai http://blog.csdn.net/thomescai (reprinted please keep)