×

Generics vs Wildcard in Java

In generic programming, the question mark (?) is often referred to as the wildcard. It stands for a mysterious type. The wildcard can be used for many different contexts, such as to specify the type of an argument, field, or local variable, or even as a return type on occasion. Contrary to arrays, a generic type's various instantiations are not consistent with one another or not even explicitly. If do? Then it is utilized as a genuine type parameter, the wildcard may help to mitigate this mismatch.

  • Java's wildcards are essentially the question marks that are used in generic programming to denote unknown types. Java Wildcard is frequently used as a return type as well as a kind of parameter, local variable, or field.
  • Multiple new structures of a generic type are incompatible with one another, not even explicitly, unlike arrays. By adding the wildcard character "?" as a genuine type parameter, we can get rid of the issue
  • The question mark (?) that you employ in Java Generics is what is known as a wildcard. The Java Wildcard can be used as a field, local variable, argument, or return type. However, we are unable to use wildcards whenever the generic class is created or when the generic function is used.
  • The use of the wildcard helps eliminate incompatibility between various instances of a generic type. Using wildcards as a true-type argument eliminates this mismatch.

In and out parameters are the two different types of parameters we pass to a method. As follows:

  1. in variable

    The Java program receives the actual data from the variable called in. There is a method called myMethod(source, destination). The source functions as an in-method variable in this technique.
  2. out variable
    The revised data is saved by the Java application in a variable called out. There is a method called myMethod(source, destination). Destination serves as the method's output variable in this method.

Types of Java Wildcards

  1. Lower Bounded Wildcard
  2. Upper Bounded Wildcards
  3. UnBoubded Wildcards

So, to sum up, every wildcard are used in the following three ways:

  • Wildcard upper bound:? extends Type.
  • Wildcard with a lower bound: super Type.
  • Unbounded Wildcard:?

Lower Bounded Wildcard

To expand the scope of the kind of variable's use, we employ the Lower Bounded wildcards. For instance, creators can use the ListInteger> to add a list of integers to our method, but by doing so, we are restricted to using only the list of numbers.

In order to save the list of integers, we may also use the ListNumber> and ListObject>. Therefore, we employ the Lower Bounded wildcard. This may be used as a wildcard character, right? and place the lower bound after that, then a superkeyword.

Example program

import java.util.Arrays;
import java.util.List;
class WildcardDemo {
public static void main(String[] args)
{
List<Integer> list1 = Arrays.asList(5, 6, 7, 8);
printOnlyIntegerClassorSuperClass(list1);
List<Number> list2 = Arrays.asList(5, 6, 7, 8);
printOnlyIntegerClassorSuperClass(list2);
}
public static void printOnlyIntegerClassorSuperClass(
List<? super Integer> list)
{
System.out.println(list);
}
}

Output

[5, 6, 7, 8]
[5, 6, 7, 8]

Upper Bounded Wildcards

The wildcard that loosens the constraint of the variable type is the Upper Bounded wildcard. In other words, we may use this kind of wildcard if we wish to loosen the constraint on the kind of variables in the procedure.

For instance, the method sum, which computes the sum of any type of variable, whether it is an int or a double variable type variable, uses the upper bound wildcard.

Example program

import java.util.Arrays;
import java.util.List;


class WildcardDemo {
public static void main(String[] args)
{
List<Integer> list1 = Arrays.asList(5, 6, 7, 8);
System.out.println("Total sum is:" + sum(list1));
List<Double> list2 = Arrays.asList(5.1, 6.1, 7.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: 26.0Total sum is:18.299999999999997

Unbounded Wildcards

When we want to indicate the kind of wildcard using the wildcard character?, we have used the Unbounded wildcards. This wildcard is typically used when the method's code makes use of Object functionality and when the method's code is independent of the parameter type.

import java.util.Arrays;
import java.util.List;
class unboundedwildcardemo {
public static void main(String[] args)
{
List<Integer> list1 = Arrays.asList(2, 4, 6);
List<Double> list2 = Arrays.asList(2.1, 3.2, 4.3);
printlist(list1);
printlist(list2);
}
private static void printlist(List<?> list)
{
System.out.println(list);
}
}

Output

[2, 4, 6][2.1, 3.2, 4.3]

Java Wildcard Use Guidelines

The instructions for using each kind of variable in the following circumstances are provided below:

  • Upper bound wildcard: We use the 'extends' keyword with a wildcard if the variable is of the in type, i.e., it is an in a variable.
  • Lower bound wildcard: We utilize the super keyword along with a wildcard if the variable is of the out type, i.e., if it is an out variable.
  • Unbounded wildcard: When we can retrieve a variable via the Object class function, we should choose to use unbounded wildcards instead.
  • No wildcard: Wildcards are not necessary if the variable falls into both the in and out categories.

Conclusion

The wildcard in Java was examined in this article. When using generics in Java, we use wildcards. We looked at how to use them for our requirements. We are able to pass the exact parameter type with the aid of wildcards.

In Java, there are three different kinds of wildcards: Upper bounded, Lower bounded, and Unbounded wildcards.


Related Topics

How to check version of java in Linux

Java is one of the most famous and thoroughly utilized programming tongues from one side of the world to the other. On the off chance that you are a Java...

2 minutes read.

Stack vs Heap in Java

In Java, whenever we declare an object or create a variable, whether it is an instance variable, local variable, or static variable, a certain memory is used to store the...

4 minutes read.

Java Program to Create Set of Pairs Using HashSet

HashSet in Java: HashSet is an assortment in Java that has a place with java.util bundle. It inside utilises HashMap to store components. It is an execution of the Set connection...

11 minutes read.

Concurrent Linked Deque in Java with Examples

Introduction Java's concurrent-linked deque, which holds its items as linked nodes, is unconstrained and thread-safe. Concurrent Linked Deque allows for element removal and addition on both sides because it implements the...

4 minutes read.

How to declare string array in Java

Introduction Array is a data structure with a fixed size, which allows us to store elements of similar type. Data of primitive types like int, char, float, string, etc. can be...

2 minutes read.

Array Programs in Java

Array Programs in Java: An array is a data structure that stores similar elements in a contiguous memory location. In Java, an array is an object that stores the same...

7 minutes read.

How to find length of integer in Java

We can find the length of the integer in many ways. The length of an integer is defined as the count of the number of digits for the given integer. These...

5 minutes read.

Alien language problem in Java

Given the alphabetic sequence of an alien language, given a sorted dictionary (array of words) for the languages. Example: Words = { "aac", "abc", "aaa" } Output c, a, b Algorithm: (1) Compare two words that...

3 minutes read.

Object Oriented Programming (OOPs)

Since the dawn of earth, we have kept on evolving. The need for evaluation comes with the aim of improving the existing systems when something inappropriate is found for the...

5 minutes read.

Package naming convention in Java

It is conceivable that many programmers will use the same name for various types, given that Java programmers from all over the world create classes and interfaces. For illustration, suppose...

4 minutes read.

Class memory in Java

Anything specifically defined in the Java code is stored either inside the heap or the stack, which is particularly significant. Stack and heap are the two kinds of memory available...

6 minutes read.

Facts about null in Java

Nearly all programming languages have a relationship with null. Hardly any programmers are unconcerned by null. The null has a java.lang.NullPointerException association in Java. Given that it is a class...

4 minutes read.

Java Integer rotateRight() method

The rotateRight() method of Java Integer class returns the value obtained by rotating the  2’s complement binary representation of the given integer value right by the specified number of bits. Syntax public...

1 minute read.

Java Integer reverseByte() method

The reverseByte() method of Java Integer class returns the value obtained by reversing the order of the bytes in the 2’s complement binary representation. Syntax public static int reverseByte (int i) Parameters The parameter...

1 minute read.

Fibonacci Series Program in Java

Fibonacci Series Program in Java using Recursion Fibonacci series is a series whose every term is comprised of adding its previous two terms, barring the first two terms 0 and 1....

3 minutes read.

How to Import Packages in Java

To know about the importing the packages of Java, we need to understand about how to packages work. Packages The package in Java is a collection of Classes and Interfaces. The packages...

3 minutes read.

How to Create an Object in Java

How to Create an Object in Java An object can be defined as a run time entity that contains the blue printof the class. It means that all the member functions...

5 minutes read.

Java instance variable

An instance in object-oriented programming (OOP) is a particular implementation of any object. Each realized version of an item, which might vary in several ways, is an instance. Instantiation is...

3 minutes read.

India Map Pattern in Java

India Map Pattern is the pattern we'll code now using Java, as demonstrated. We will use a star in Java to print our India map.The specialty is that we will only...

4 minutes read.

URLConnection class in Java

A communication channel between the URL and the program is represented by the Java URLConnection class. It may be utilized to read from and write to the given resource the...

4 minutes read.