我已经问过这个问题了,我还有一些关于使用的问题 我上过课。 见下面的代码。
import java.util.*;
class Pair{
int toWhere;
int weight;
}
public class Test{
public static void main(String[] args){
ArrayList[] arr = new ArrayList[2];
Pair p = new Pair();
for(int i=0; i<arr.length; i++)
arr[i] = new ArrayList<Pair>();
p.toWhere = 1;
p.weight = 2;
arr[0].add(p);
System.out.println(p); // gives me Pair@525483cd
System.out.println(arr[0].get(0)); // gives me exactly the same, Pair@525483cd
System.out.println(p.toWhere); // gives me no error, and is 1
System.out.println(arr[0].get(0).toWhere); // gives me an error
}
}
我的问题是这个。
p和arr[0].get(0)
的值(地址?我猜)是一样的。
但为什么p.toWhere
给了我准确的价值和
arr[0].get(0).toWhere
没有?
答案 0 :(得分:2)
那是因为编译器不知道arr
是ArrayList
Pair
的数组。您需要输入arr:
List<Pair>[] arr = new ArrayList[2];
现在,当您使用arr[0].get(0)
时,编译器知道get
会返回Pair
(而不是代码中的Object
),因此Pair
'方法可用。