如果可能,如何从另一个方法的return调用method
例如..。
class Example {
public static void main(String[] args) {
Point t1 = new Point(0,0);
Point t2 = new Point(0,1);
ArrayList pointContainer = new ArrayList();
pointContainer.add(0,t1);
pointContainer.add(0,t2); // We now have an ArrayList containing t1 & t2
System.out.println(pointContainer.get(1).getLocation()); // The problem area
}
}在这个写得很糟糕的示例中,我试图对pointContainer的索引项1调用getLocation()方法(java.swing.awt的一部分)。
当尝试编译程序时,我得到以下错误...
HW.java:20: error: cannot find symbol
System.out.println(test.get(1).getLocation());
^
symbol: method getLocation()
location: class Object有人能帮我解决这个问题吗?
发布于 2012-06-21 08:19:34
首先,输入您的ArrayList,这样Java就可以知道从它出来的是什么对象。
List<Point> pointContainer = new ArrayList<Point>();然后,您从该ArrayList检索的任何对象都将是Point类型,因此您可以对它们执行操作。
发布于 2012-06-21 08:26:06
在您的示例中,需要显式转换为Point,然后调用所需的方法。否则你需要用java泛型的方式定义arraylist,就像@Makoto提到的那样。
投射方式是
((Point)pointContainer.get(1)).getLocation()
https://stackoverflow.com/questions/11129957
复制相似问题