What is the purpose of List<?> if one can only insert a null value?
public static void printList(List<?> list) {
for (Object elem: list)
System.out.print(elem + " ");
System.out.println();
}
You use the unbounded wildcards when the list (or the collection) is of unknown types.
What is the purpose of List if one can only insert a null value?
Based on the information provided in the link, it says that: It's important to note that List
https://stackoverflow.com/questions/35272848/java-generics-unbound-wildcards-vs-object
Java generics, Unbound wildcards vs
https://stackoverflow.com/questions/18176594/when-to-use-generic-methods-and-when-to-use-wild-card
When to use generic methods and when to use wild-card?
I am reading about generic methods from OracleDocGenericMethod. I am pretty confused about the comparison when it says when to use wild-card and when to use generic methods. Quoting from the docume...
stackoverflow.com
https://www.tutorialspoint.com/java_generics/java_generics_wildcards_guidelines.htm
Java Generics - Guidelines for Wildcard Use
Java Generics - Guidelines for Wildcard Use Wildcards can be used in three ways − Upper bound Wildcard − ? extends Type. Lower bound Wildcard − ? super Type. Unbounded Wildcard − ? In order to decide which type of wildcard best suits the condition,
www.tutorialspoint.com
package com.tutorialspoint;
import java.util.ArrayList;
import java.util.List;
public class GenericsTester {
//Upper bound wildcard
//in category
public static void deleteCat(List<? extends Cat> catList, Cat cat) {
catList.remove(cat);
System.out.println("Cat Removed");
}
//Lower bound wildcard
//out category
public static void addCat(List<? super RedCat> catList) {
catList.add(new RedCat("Red Cat"));
System.out.println("Cat Added");
}
//Unbounded wildcard
//Using Object method toString()
public static void printAll(List<?> list) {
for (Object item : list)
System.out.println(item + " ");
}
public static void main(String[] args) {
List<Animal> animalList= new ArrayList<Animal>();
List<RedCat> redCatList= new ArrayList<RedCat>();
//add list of super class Animal of Cat class
addCat(animalList);
//add list of Cat class
addCat(redCatList);
addCat(redCatList);
//print all animals
printAll(animalList);
printAll(redCatList);
Cat cat = redCatList.get(0);
//delete cat
deleteCat(redCatList, cat);
printAll(redCatList);
}
}
class Animal {
String name;
Animal(String name) {
this.name = name;
}
public String toString() {
return name;
}
}
class Cat extends Animal {
Cat(String name) {
super(name);
}
}
class RedCat extends Cat {
RedCat(String name) {
super(name);
}
}
class Dog extends Animal {
Dog(String name) {
super(name);
}
}
Cat Added
Cat Added
Cat Added
Red Cat
Red Cat
Red Cat
Cat Removed
Red Cat