'E 扩展了在类 Vector 中声明的对象,即使在使用泛型之后



我已经尝试编译以下代码很长时间了,但我总是收到警告:

warning: [unchecked] unchecked call to addElement(E) as a member of the raw type Vector
v.addElement(obj);
^
where E is a type-variable:
E extends Object declared in class Vector

这种情况正在发生,尽管我使用泛型声明了我的Vector。你能帮我一下吗?

import java.util.*;
public class Employee {

String name;
float sal;
int id;
public static void main(String args[]) {
Vector<Employee> vec = new Vector<Employee>();
int n, ch;
System.out.println("Enter the number of employees");
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
Create(vec, n);
System.out.println("Enter any 1 of the following choices ");
System.out.println("1 to insert a new record");
System.out.println("2 to delete an Employee record by name");
System.out.println("3 to delete by the ID");
ch = sc.nextInt();
switch (ch) {
case 1:
{
}
case 2:
{
}
}
}
public static void Create(Vector v, int n) {
String ename;
float esal;
int eid;
int i;
Scanner sc1 = new Scanner(System.in);
for (i = 0; i < n; i++) {
System.out.println("Enter the ID");
eid = sc1.nextInt();
System.out.println("Enter the name");
ename = sc1.next();
System.out.println("Enter the salary");
esal = sc1.nextFloat();
Employee obj = new Employee();
obj.name = ename;
obj.sal = esal;
obj.id = eid;
v.addElement(obj);
}
}
}

在这个程序中,我声明了一个类Employee,并打算调用Create方法n次,以便在执行其他函数之前添加n员工的详细信息。然而,我最初收到了Xlint:unchecked警告,在使用Xlint:unchecked文件名再次编译后,我仍然收到了这个警告,无法继续操作。你能帮帮我吗?

Create方法中的参数v被声明为原始类型。尝试将泛型类型添加到参数声明中,例如:

public static void Create(Vector<Employee> v, int n) {

您可以在以下链接中阅读更多关于原始类型的信息:

https://docs.oracle.com/javase/tutorial/java/generics/rawTypes.html

最新更新