开发者

java Pair and ArrayList question

I already asked this question and I got additional question about using class I made myself. see code below.

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

my question is this. values of p and arr[0].get(0) (which is address? I guess) is the same. but why does p.toWhere give me the accurate value and arr[0].get(0).toWhere does not?


That's because the compiler doesn't know that arr is an array of ArrayList of Pair. You need to type arr:

List<Pair>[] arr = new ArrayList[2];

Now when you use arr[0].get(0), the compiler knows that get returns a Pair (not an Object as in your code), so Pair's methods are available.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜