The question mark (?) is known as the wildcard in generic programming. It represents an unknown type. The wildcard can be used in a variety of situations such as the type of a parameter, field, or local variable; sometimes as a return type. Unlike arrays, different instantiations of a generic type are not compatible with each other, not even explicitly. This incompatibility may be softened by the wildcard if ? is used as an actual type parameter.
Types of wildcards in Java
1. Upper Bounded Wildcards:
These wildcards can be used when you want to relax the restrictions on a variable. For example, say you want to write a method that works on List < Integer >, List < Double >, and List < Number >, you can do this using an upper bounded wildcard.
To declare an upper-bounded wildcard, use the wildcard character (‘?’), followed by the extends keyword, followed by its upper bound.
public static void add(List<? extends Number> list)
Implementation:
Java
import java.util.Arrays;
import java.util.List;
class WildcardDemo {
public static void main(String[] args)
{
List<Integer> list1 = Arrays.asList( 4 , 5 , 6 , 7 );
System.out.println( "Total sum is:" + sum(list1));
List<Double> list2 = Arrays.asList( 4.1 , 5.1 , 6.1 );
System.out.print( "Total sum is:" + sum(list2));
}
private static double sum(List<? extends Number> list)
{
double sum = 0.0 ;
for (Number i : list) {
sum += i.doubleValue();
}
return sum;
}
}
|
Output
Total sum is:22.0
Total sum is:15.299999999999999
Explanation:
In the above program, list1 and list2 are objects of the List class. list1 is a collection of Integer and list2 is a collection of Double. Both of them are being passed to method sum which has a wildcard that extends Number. This means that list being passed can be of any field or subclass of that field. Here, Integer and Double are subclasses of class Number.
2. Lower Bounded Wildcards:
It is expressed using the wildcard character (‘?’), followed by the super keyword, followed by its lower bound: <? super A>.
Syntax: Collectiontype <? super A>
Implementation:
Java
import java.util.Arrays;
import java.util.List;
class WildcardDemo {
public static void main(String[] args)
{
List<Integer> list1 = Arrays.asList( 4 , 5 , 6 , 7 );
printOnlyIntegerClassorSuperClass(list1);
List<Number> list2 = Arrays.asList( 4 , 5 , 6 , 7 );
printOnlyIntegerClassorSuperClass(list2);
}
public static void printOnlyIntegerClassorSuperClass(
List<? super Integer> list)
{
System.out.println(list);
}
}
|
Output
[4, 5, 6, 7]
[4, 5, 6, 7]
Explanation:
Here arguments can be Integer or superclass of Integer(which is Number). The method printOnlyIntegerClassorSuperClass will only take Integer or its superclass objects. However, if we pass a list of types Double then we will get a compilation error. It is because only the Integer field or its superclass can be passed. Double is not the superclass of Integer.
Note: Use extend wildcard when you want to get values out of a structure and super wildcard when you put values in a structure. Don’t use wildcard when you get and put values in a structure. You can specify an upper bound for a wildcard, or you can specify a lower bound, but you cannot specify both.
3. Unbounded Wildcard:
This wildcard type is specified using the wildcard character (?), for example, List. This is called a list of unknown types. These are useful in the following cases –
- When writing a method that can be employed using functionality provided in Object class.
- When the code is using methods in the generic class that doesn’t depend on the type parameter
Implementation:
Java
import java.util.Arrays;
import java.util.List;
class unboundedwildcardemo {
public static void main(String[] args)
{
List<Integer> list1 = Arrays.asList( 1 , 2 , 3 );
List<Double> list2 = Arrays.asList( 1.1 , 2.2 , 3.3 );
printlist(list1);
printlist(list2);
}
private static void printlist(List<?> list)
{
System.out.println(list);
}
}
|
Output
[1, 2, 3]
[1.1, 2.2, 3.3]
Similar Reads
TreeMap tailMap() Method in Java
The java.util.TreeMap.tailMap(from_Key) method in Java is used to get a part or view of the map whose keys are greater than equal to the from_key in the parameter. Any changes made in one map will reflect the change in the other map. Syntax: Tree_Map.tailMap(from_Key) Parameters: The method takes on
3 min read
Java 8 Stream
Introduction to Stream, Java Intstream, Jaa Longstream , Java Doublestream anyMatch() noneMatch() mapToLong() findAny()forEachOrdered() forEach() allMatch() filter() findFirst() flatMapToInt() mapToInt() map() peek() counting()Iterator()Generate()Skip()SummaryStatistics()Builder()Empty()Stream toArr
1 min read
LongStream mapToObj() in Java
LongStream mapToObj() returns an object-valued Stream consisting of the results of applying the given function. Note : LongStream mapToObj() is a intermediate operation. These operations are always lazy. Intermediate operations are invoked on a Stream instance and after they finish their processing,
2 min read
LongStream generate() method in Java
LongStream generate(LongSupplier s) returns an infinite sequential unordered stream where each element is generated by the provided LongSupplier(a supplier of long-valued results). This is suitable for generating constant streams, streams of random elements, etc. Syntax : static LongStream generate(
1 min read
IntStream mapToObj() in Java
IntStream mapToObj() returns an object-valued Stream consisting of the results of applying the given function. Note : IntStream mapToObj() is a intermediate operation. These operations are always lazy. Intermediate operations are invoked on a Stream instance and after they finish their processing, t
2 min read
Shorts Class | Guava | Java
Shorts is a utility class for primitive type short. It provides Static utility methods pertaining to short primitives, that are not already found in either Short or Arrays. Declaration : @GwtCompatible(emulated=true) public final class Shorts extends Object Below table shows the Field summary for Gu
3 min read
Stream builder() in Java with Examples
Stream builder() returns a builder for a Stream. Syntax : static <T> Stream.Builder<T> builder() where, T is the type of elements. Return Value : A stream builder. Example 1 : // Java code for Stream builder() import java.util.*; import java.util.stream.Stream; class GFG { // Driver code
2 min read
Stream toArray() in Java with Examples
Stream toArray() returns an array containing the elements of this stream. It is a terminal operation i.e, it may traverse the stream to produce a result or a side-effect. After the terminal operation is performed, the stream pipeline is considered consumed, and can no longer be used. Syntax : Object
2 min read
LongStream max() in Java with examples
java.util.stream.LongStream in Java 8, deals with primitive longs. It helps to solve the problems like finding maximum value in array, finding minimum value in array, sum of all elements in array, and average of all values in array in a new way. LongStream max() returns an OptionalLong describing th
2 min read
Stream anyMatch() in Java with examples
Stream anyMatch(Predicate predicate) returns whether any elements of this stream match the provided predicate. It may not evaluate the predicate on all elements if not necessary for determining the result. This is a short-circuiting terminal operation. A terminal operation is short-circuiting if, wh
2 min read