Wildcard can be used with <> operator in a generics concept introduced in java 5, used to represent unknown type. Generics is used to define a class with member in generalized format.If you want to provide facility that while creating the object, user will specify the type of member then you can use the concept of generics. It can be used only for the instance member can't be used with static member cause memory for static will be allocated only once.
Wildcard concept introduced in generics to restrict unknow type, let's say I have list which has wildcard and this wildcard extend Number wrapper class. That means list can work with Integer, Long, Short, Byte cause they extend Number wrapper class but not with String as String class do not extends Number wrapper class.
List<? extends Number> lt = new ArrayList<>();
Coming to you program, you have used wrong syntax, as i have mentioned wildcard can be used with <> operator.
We can't use wildcard while instantiating class like mentioned bellow -
List<?> lt = new ArrayList<?>();
but we can use generics to provide the field as unknown type like I,N,S in employee class. It's type we will provide while creating the object of the class -
class Employee<I,N,S>
{
I eid;
N empName;
S empSalary;
}
class Name
{
String firstName;
String middleName;
String lastName;
}
class salary
{
double basic;
float it;
float tds;
double netsal;
}
class CustomId
{
int empId;
String department;
int branchId;
}
main method
------------
Employee<Integer,String,Double> emp = new Employee<>();
Employee<String,Name,Salary> emp2 = new Employee<>();
Employee<CustomId,String,Salary> emp3 = new Employee<>();
Wildcard as method parameter -
public void sortList(List<?> lt)
{
// code to sort the list whether it is integer, String etc
}
call sortList() method
-----------------------
List<String> lt = new List<>();
lt.add("sss");
lt.add("aaa");
sortList(lt);
List<Integer> lt = new List<>();
lt.add(11);
lt.add(12);
sortList(lt);
Declaring local variable as wildcard -
List<?> lt = new ArayList<String>();
List<?> lt = new ArayList<Integer>();
We can use wildcard and generics as return type of method.
Here is the example of generics as return type of method -
public T getName(ClassName obj, Key key)
{
return (Type<T>)obj.getType(Key);
}
Here is the example of wildcard as return type of method -
List<?> method(List<?> data)
{
return data;
}