The function of generics is to limit the parameter type and make the code more rigorous. In future use, there will be no errors in parameter calls.
Let's look at the implementation of Java internal class generics.
1 // IntelliJ API Decompiler stub source generated from a class file 2 // Implementation of methods is not available 3 4 package java.util; 5 6 public interface Map<K, V> { 7 8 int size(); 9 10 boolean isEmpty();11 12 boolean containsKey(java.lang.Object o);13 14 boolean containsValue(java.lang.Object o);15 16 V get(java.lang.Object o);17 18 V put(K k, V v);19 20 V remove(java.lang.Object o);21 22 void putAll(java.util.Map<? extends K,? extends V> map);23 24 void clear();25 26 java.util.Set<K> keySet();27 28 java.util.Collection<V> values();29 30 java.util.Set<java.util.Map.Entry<K,V>> entrySet();31 32 boolean equals(java.lang.Object o);33 34 int hashCode();35 36 static interface Entry<K, V> {37 38 K getKey();39 40 V getValue();41 42 V setValue(V v);43 44 boolean equals(java.lang.Object o);45 46 int hashCode();47 }48 }
This is the implementation of the map interface in Java.
Note the methods defined in the map interface,
1 V put(K k, V v);
The Return Value Type and parameter type are both K and V. That is to say, it does not limit a strong type, such as integer or string.
You can set the generic type to integer or string based on your needs to limit future input and parameter types and call to parameter methods.
We usually write this when calling
1 Map<String, String> strMap = new HashMap<String, String>();
Here, when we perform the put operation on strmap, the input type can only be string
The element obtained from strmap is also the most string class.
The types in generics can also support inheritance.
1 class Sort<E extends Comparable<E>> { /** **/ }