-
Notifications
You must be signed in to change notification settings - Fork 0
Wildcards in Java
- Upper Bound Wildcards
Let's say you want to create a list of numbers. It doesn't matter if it is an integer or a double. Even if you did this:
ImList<Integer> list = new ImList<>()
Then, the list will only take in integers.
Now, doing this would give you a compile-time error.
list = list.add(2.2)
Even if a ImList was created that took in Number:
ImList<Number> list = new ImList<>()
If you added a Integer into the list first, you would not be able to add a Double or any other type into the list
list = list.add(1)add(2.2) //compilation error
This is when upper bounded wildcards are useful!
ImList<? extends Number> list = new ImList<>()
Doing this will allow you to add any subtype of Number into list.
- Lower bound wildcard
We use the Lower Bounded wildcards to widen the use of the type of variable. For example, if we want to add the list of integers in our method we can use the List, but using this we will be bound to use only the list of integers.
So here, we can also use the ImList and ImList to store the list of integers. So we use the Lower Bounded wildcard to achieve this.
ImList<? super Number> list = new ImList<>()