1

如果可能的话,如何method从另一个方法调用 a return

例如...

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
    }
}

在写得不好的例子中,我试图在 的索引项 1 上调用getLocation()方法(的一部分) 。java.swing.awtpointContainer

尝试编译程序时,出现以下错误...

HW.java:20: error: cannot find symbol
        System.out.println(test.get(1).getLocation());
                                  ^
  symbol:   method getLocation()
  location: class Object

有人可以帮我解决这个问题。

4

2 回答 2

4

首先,键入您的 ArrayList,以便 Java 可以知道从中产生了哪些对象。

List<Point> pointContainer = new ArrayList<Point>();

然后,您从该 ArrayList 检索的任何对象都将是 type Point,因此您可以对它们执行操作。

于 2012-06-21T00:19:33.800 回答
1

在您的情况下,您需要对 the 进行显式转换Point,然后调用预期的方法。否则,您需要使用@Makoto 提到的 java 泛型方式定义数组列表。

铸造方式是

((Point)pointContainer.get(1)).getLocation()

于 2012-06-21T00:26:06.413 回答