我正在做作业,所以我只想修复我的编译错误,这样我就可以继续工作。我需要创建一个 PointList 类,将 Point 对象列表保存在 ArrayList 中。 PointList 类应该接受作为 Point 类实例或 Point 子类的任何对象。
我不断收到编译器错误,提示
> required: Point<Integer>
found: no arguments
reason: actual and formal argument lists differ in length
where E is a type-variable:
E extends Object declared in class PointList
我真的不明白我错过了什么,我已经读完了这本书,似乎不明白为什么会出现这个错误。我已经制作了 Point 类并完成了测试,但似乎无法编译它。
public class PointListTest{
public static void main(String[] args){
//create point ints
Point<Integer> pointOne = new Point<Integer>(1,2);
Point<Integer> pointTwo = new Point<Integer>(3,4);
Point<Integer> pointThree = new Point<Integer>(5,6);
//make object PointList pointlist for int
PointList<Point<Integer>> newPointList = new PointList<Point<Integer>>();
//add points to list
newPointList.add(pointOne);
newPointList.add(pointTwo);
newPointList.add(pointThree);
这就是我到目前为止的 PointList
public class PointList<E>{
private ArrayList<Point> myPoint;
E data;
public PointList(E obj){
ArrayList<Point> myPoint = new ArrayList<Point>();
data = obj;
}
}
点类别
public class Point<T extends Number>{
//field values
private T xCordinate;
private T yCordinate;
//constructor
//@param x the x cordinate
//@param y the y cordinate
public Point(T x, T y){
xCordinate = x;
yCordinate = y;
}//end constructor
public void setX(T x){
xCordinate = x;
}//end setX
public void setY(T y){
yCordinate = y;
}//end setY
public T getX(){
return xCordinate;
}//end getX
public T getY(){
return yCordinate;
}//end getY
}//end pointlist
如果我能够编译它,以便我可以继续研究它,我将非常感激。
最佳答案
您的 PointList 具有唯一一个带有一个参数的构造函数:
public PointList(E obj){
ArrayList<Point> myPoint = new ArrayList<Point>();
data = obj;
}
但是您尝试使用零参数调用构造函数:
PointList<Point<Integer>> newPointList = new PointList<Point<Integer>>();
所以,编译器找不到对应的。请参阅Providing Constructors for Your Classes教程和Constructor overloading in Java .
关于java - Java 构造函数中的泛型错误无法应用于给定类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54758250/