1, Questions
1. Define a method, which is used to print all the data in the collection of any parameterized type. How to define this method?
Wrong way
public static void printCollection(Collection<Object> cols) { for(Object obj:cols) { System.out.println(obj); } /* cols.add("string");//You're right cols = new HashSet<Date>();//Error will be reported!*/ }
The right way
public static void printCollection(Collection<?> cols) { for(Object obj:cols) { System.out.println(obj); } //cols.add("string"); / / error, because it does not know that its future match must be String cols.size();//Yes, this method has nothing to do with type parameters cols = new HashSet<Date>(); }
Full code
package staticimport.generic; import java.util.ArrayList; import java.util.Collection; import java.util.List; /*** * * Defines a method for printing all data in a collection of any parameterized type * * @author Liu * */ public class GenericTest2 { public static void main(String[] args) { List<Integer> list = new ArrayList<>(); list.add(1); list.add(5); list.add(2); printCollection(list); System.out.println("--------------------"); List<String> list2 = new ArrayList<>(); list2.add("aaa"); list2.add("bbb"); list2.add("ccc"); printCollection(list2); } private static void printCollection(Collection<?> collection) { System.out.println(collection.size()); for(Object object : collection){ System.out.println(object); } } }
Summary
You can use the wildcard to refer to various other parameterized types. The variables defined by the wildcard are mainly used as references. You can call methods that are not related to the parameterization, not methods that are related to the parameterization.
2. Limit the upper boundary of wildcards
Correct: vector <? Extends number > x = new vector < integer > (); Error: vector <? Extends number > x = new vector < string > ();
3. Limit the lower boundary of wildcards
Correct: vector <? Super integer > x = new vector < number > (); Error: vector <? Super integer > x = new vector < byte > ();
Note: qualified wildcards always include themselves
2, A comprehensive case of generic set classes
package GenericTest2; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; /*** * * Traverse Map in a generic way * * @author Liu * */ public class GenericTest3 { public static void main(String[] args) { Map<String, Integer> map = new LinkedHashMap<>(); map.put("xa", 30); map.put("james", 33); map.put("jordan", 50); Set<Map.Entry<String, Integer>> entrySet = map.entrySet(); for(Map.Entry<String, Integer> entry : entrySet){ System.out.println(entry.getKey() + ":" + entry.getValue()); } } }