[英]Java Generics - why doesn't it output the variables?
I've searched and searched, and I feel like I'm missing something really minor about the steps of using them. 我已经搜索了很多,感觉就像我在使用它们的步骤上缺少了一些细微的东西。
Class file for the generic: 通用的类文件:
public class Point <T> {
private T xPos, yPos;
public Point(T xPos, T yPos) {
this.xPos = xPos;
this.yPos = yPos;
}
public T getXPos() {
return xPos;
}
public void setXPos(T xPos) {
this.xPos = xPos;
}
public T getYPos() {
return yPos;
}
public void setYPos(T yPos) {
this.yPos = yPos;
}
}
Demo file: 演示文件:
public class PointTester {
public static void main(String[] args) {
Point<Integer> point1 = new Point<Integer>(10,20);
Point<Double> point2 = new Point<Double>(14.5, 15.6);
Point<String> point3 = new Point<String>("topleftx", "toplefty");
System.out.println(point1);
System.out.println(point2);
System.out.println(point3);
}
}
To define how a class in printed, you need to override the standard toString()
method. 要定义类的打印方式,您需要重写标准的
toString()
方法。 In your example, you'd do something like 在您的示例中,您将执行以下操作
public String toString() {
return "(" + xPos + ", " + yPos + ")";
}
I assume that it is printing 'something' but that the 'something' is un-helpful. 我认为它正在打印“某物”,但是“某物”没有帮助。
I believe that the thing that you are missing is a 'toString' method. 我相信您所缺少的是一个“ toString”方法。
You need to override the the toString
in Point
that will return what you want to print. 您需要重写
Point
中的toString
,它将返回您要打印的内容。
eg 例如
@Override
public String toString() {
return /* what you want ... */;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.