java泛型构造函数未定义
我正在学习java和泛型,遇到了一些问题。我已经阅读了Stackoverflow上发布的generic上的所有问题,但无法理解为什么会发生此错误java泛型构造函数未定义,java,generics,Java,Generics,我正在学习java和泛型,遇到了一些问题。我已经阅读了Stackoverflow上发布的generic上的所有问题,但无法理解为什么会发生此错误 class Student{ String name; float marks; Student(String name,float marks){ this.name = name; this.marks = marks; } } public class GenericClas
class Student{
String name;
float marks;
Student(String name,float marks){
this.name = name;
this.marks = marks;
}
}
public class GenericClassEx<T> {
T obj;
GenericClassEx(T data){
this.obj = data;
}
public T getObject(){
return this.obj;
}
public static void main(String[] args) {
Float d = new Float(10);
GenericClassEx<Student> iobj= new GenericClassEx <Student> ("prince",d);
System.out.println(iobj.getObject());
}
}
当我运行这段代码时,它说
GenericClassEx.java:28: error: constructor GenericClassEx in class GenericClassEx<T> cannot be applied to given types;
GenericClassEx<Student> iobj= new GenericClassEx <Student> ("prince",d);
^
required: Student
found: String,Float
reason: actual and formal argument lists differ in length
where T is a type-variable:
T extends Object declared in class GenericClassEx
Note: GenericClassEx.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
1 error
您需要将Student对象传递给构造函数GenericClassExT data。相反,您将传递两个参数,prince和d 替换
GenericClassEx<Student> iobj= new GenericClassEx <Student> ("prince",d);
Float d = new Float(10);
与
但是我从中学习的代码没有使用new,他的代码是如何工作的?@PrinceBhatia——构造函数genericsclassext data只需要一个对象作为参数。不是吗?并且,您使用new Studentprince,d创建了一个Student对象。除了一条语句,您还可以使用以下两条语句来完成:Student Student=new Studentprince,d;GenericClassEx iobj=新的GenericClassExstudent@PrinceBhatia您提供的代码显然不起作用-您是否从教程中错误地复制了它,或者教程本身有问题是另一个主题,也是一个不相关的主题。这个答案解决了你的问题,故事结束了。
Float d = new Float(10);
Float d = Float.valueOf(10);