Wildcard characters in java generics
Overview
It was easy to understand the wildcard content in java at the beginning, but when it comes to wildcards, I am dizzy, because I learned the guiding ideology of the java content, yes.. net, but the wildcard in java ,. net does not have such a concept, so I took the time to learn about it. The following example shows how to use wildcards.
Instance code
package com.tgb.mydemo;import java.util.ArrayList;import java.util.List;public class Test {public static void main(String[] args){Integer[] integers = {1,2,3,4,5};ArrayList
integerList = new ArrayList
();for (Integer integer : integers) {integerList.add(integer);}System.out.println("Total of the elements in integerList:" + sum(integerList));Double[] doubles = {1.1,2.2,3.3,4.4,5.5};ArrayList
doubleList = new ArrayList
();for (Double element : doubles) {doubleList.add(element);}System.out.println("Total of the elements in integerList:" + sum(doubleList));Number[] numbers = {1.1,2.2,3,4,5.5};ArrayList
numberList = new ArrayList
();for (Number element : numbers) {numberList.add(element);}System.out.println("Total of the elements in integerList:" + sum(numberList));}public static double sum(ArrayList
list){double total = 0;for(Number element : list ){total += element.doubleValue();}return total;}}
Note: Number is the parent class of Double and Integer.
If you put the above Code in java IDE, a syntax error may occur. Why? Because the parameter type of the sum function is ArrayList When we use the sum function, we pass the ArrayList Or ArrayList Type. Although the Number type is the parent class of the Double and Integer types, the compiler does not set the ArrayList And ArrayList (ArrayList ). To solve this problem, and "?" That is, the wildcard, which is why the wildcard appears.
Differences between wildcard and generic Constraints
The generic constraints mentioned here are generic constraints used to define generic classes. From this sentence, we will know that generic constraints are used to define generic classes, it is a constraint on Generics when defining generic classes. Wildcards are a constraint on types when using generic classes.
Wildcard constraint types
There are three types of wildcard constraints.
No constraints: That is, the type parent class must be of the Object type.
Upper Limit constraint: That is, the type must be a subclass of type 1 or type 1.
Deprecation constraints: That is, the type must be the parent class of type 1 or type 1.
Summary
Wildcard makes it possible for us to use a generic class to give a specific type. By parameterization the specific type, the end user's range becomes smaller.