0

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?

1
  • May be you should use this instead ArrayList<Pair>[] Commented Aug 1, 2011 at 4:49

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.