我已经问过这个问题,并且我还有关于使用的其他问题 我自己做的课。 请参阅下面的代码。
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
没有吗?
最佳答案
这是因为编译器不知道arr
是ArrayList
of Pair
的数组。您需要输入 arr:
List<Pair>[] arr = new ArrayList[2];
现在,当您使用 arr[0].get(0)
时,编译器知道 get
返回一个 Pair
(而不是 Object
(如您的代码中所示),因此 Pair
的方法可用。
关于java Pair 和 ArrayList 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6894283/