views:

58

answers:

3

I have a class called Coordinate, and am building a vector of these coordinate objects. Here's what the Coordinate class looks like - it's pretty simple:

    class Coordinate {
      public int x;
      public int y;

      // constructor
      public Coordinate(int x, int y) {
        this.x = x;
        this.y = y;
      }
}

My question is, after making a vector holding several instances of this class, how would I access the x or y values of a Coordinate object at a given index of the vector? As an example:

v = new Vector<Coordinate>();
Coordinate a = new Coordinate(2, 3);
Coordinate b = new Coordinate(1, 4);
v.add(a);    
v.add(b);

How could I access the y value of the object at index0 of the vector and compare it to the y value of the object at index1? Thanks!

+3  A: 

The get method of the Vector returns the actual object in the vector. So here is how you would compare the y values:

if (v.get(0).y == v.get(1).y)
Chris Knight
A: 

Use the elementAt() method to get a reference to the contained object, then access its y attribute.

Ignacio Vazquez-Abrams
A: 

Simply put, you can reach it via the method get(int) of Vector:

boolean result = v.get(0).y == v.get(1).y;

In such cases, I suggest you to refer to documentation. Also consider encapsulating your fields for data protection.

Erkan Haspulat