38 _ wildcard extended application, 38 wildcard
- Problem:
- Define a method to print all data in a set of any parametric types. How can this method be defined?
-
Incorrect Method
Public static void printCollection (Collection <Object> cols) {for (Object obj: cols) {System. out. println (obj);}/** cols. add ("string"); // Yes, cols = new HashSet <Date> (); // an error is reported! */}
Public static void printCollection (Collection <?> Cols) {for (Object obj: cols) {System. out. println (obj);}/** cols. add ("string"); // error, because he does not know that his future match must be Stirng cols. size (); // yes. This method has nothing to do with type parameters. cols = new HashSet <Date> (); // yes, it can be used with Collection <?> Draw equal sign */}
- Summary:
- Use? Wildcards can reference other parameterized types ,? Variables defined by Wildcards are mainly used as references. You can call Methods unrelated to parameterization, rather than methods related to parameterization.
In, the Red Cross method is related to the type, when using wildcard? Cannot be called.
Collection <?> A can match any parameterized type, but only later will know what type is matched,
A = new ArrayList <Integer> (); and a = new ArrayList <String>. add (new Date); or. add ("abc"); none of them work.
Objects in Cols <Object> only indicate that the parameters received by methods in the Cols <Object> instance Object are
Cols <Object> is a specific type, and new HashSet <Date> is also a specific type. The two are not compatible.
- In generics? Wildcard Extension