在 java 5 中引入的泛型概念中,通配符可以与<> 运算符一起使用,用于表示未知类型。泛型用于以通用格式定义具有成员的类。如果您想提供在创建对象时用户指定成员类型的便利,那么您可以使用泛型的概念。它只能用于实例成员不能与静态成员一起使用,因为静态内存只会分配一次。
泛型中引入了通配符概念以限制未知类型,假设我有一个包含通配符的列表,并且这个通配符扩展了 Number 包装类。这意味着列表可以与 Integer、Long、Short、Byte 一起使用,因为它们扩展了 Number 包装类,但不能与 String 一起使用,因为 String 类不扩展 Number 包装类。
List<? extends Number> lt = new ArrayList<>();
来到你的程序,你使用了错误的语法,因为我已经提到通配符可以与 <> 运算符一起使用。
我们不能在实例化类时使用通配符,如下所述 -
List<?> lt = new ArrayList<?>();
但我们可以使用泛型将字段提供为未知类型,例如员工类中的 I、N、S。这是我们在创建类的对象时将提供的类型 -
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<>();
通配符作为方法参数 -
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);
将局部变量声明为通配符 -
List<?> lt = new ArayList<String>();
List<?> lt = new ArayList<Integer>();
我们可以使用通配符和泛型作为方法的返回类型。这是泛型作为方法的返回类型的示例 -
public T getName(ClassName obj, Key key)
{
return (Type<T>)obj.getType(Key);
}
这是通配符作为方法返回类型的示例 -
List<?> method(List<?> data)
{
return data;
}