[英]java Generic constructor undefined
我正在學習 java 和 generics 並遇到了一些問題。 我已閱讀 Stackoverflow 上發布的有關泛型的所有問題,但不明白為什么會發生此錯誤
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
的 object 傳遞給構造函數GenericClassEx(T data)
。 取而代之的是,您將兩個 arguments、 "prince"
和d
傳遞給它。
代替
GenericClassEx<Student> iobj= new GenericClassEx <Student> ("prince",d);
和
GenericClassEx<Student> iobj = new GenericClassEx<Student>(new Student("prince", d));
附帶說明一下,構造函數Float(double value)
自 Java-9 以來已被棄用。
代替
Float d = new Float(10);
和
Float d = Float.valueOf(10);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.