views:

141

answers:

3

I have an array of numbers and would like to retrieve one of the values from location "index". I've looked at the Java documentation http://java.sun.com/j2se/1.5.0/docs/api/java/lang/reflect/Array.html but my code still isn't compiling.

here is my method:

public class ConvexPolygon implements Shape
{
    java.awt.Point[] vertices;

    public ConvexPolygon(java.awt.Point[] vertices) 
    {
        this.vertices = vertices;
        this.color = color;
        this.filled = filled;
    }

java.awt.Point getVertex(int index)
{  
    Point vertex;
    vertex =  get(Point vertices, int index);  
}

I have numbers in an array representing Points. The value index is going to be the location of the array verities. What can I do to make this work? Thanks !

+3  A: 

I think you're just looking for:

 Point vertex = vertices[index];

At least - if you're not looking for that, please expand on what the difference is between using the array index and what you do want :)

Jon Skeet
Okay, I feel really dumb now. I just transitioned from programming in C so this should have been a nobrainer. But retrieving things in Java usually require the get so I was thinking along that path. Thanks though! it works
Kevin Duke
@Kevin: Yes, Java is slightly odd in its handling of arrays. They're treated very specially - they don't implement any interfaces, and they have the extra syntax. C# is a *bit* saner, in that you can define indexers on your own types, and arrays implement appropriate interfaces, but they're still "special" in various ways.
Jon Skeet
+1  A: 

Hope it works!

java.awt.Point getVertex(int index)
{  
    return vertices[index];
}
craftsman
+3  A: 

In Java, array indexes are denoted by the square brackets. You can replace your get(vertices, index) call like so:

  vertex = vertices[index];

In looking at your code, it appears you are coming from a language that defines a global get() function for such operations. Be aware that, in Java, there are no global functions. Each class you create defines its own functions, and any function call without an object or class preceding it is assumed to be defined in the local class.

So, your call to get(Point[], int) could work only if you define that function on this class:

  public Point get(Point[] vertices, int index) {
     return vertices[index];
  }

Or define it statically on another class and precede the call with the class name:

public class PointArrayHelper {

  public static Point get(Point[] vertices, int index) {
    return vertices[index];
  }
}

PointArrayHelper.get(vertices, index);

Now, be warned that I don't think you should do either of these! I just thought it might help you understand Java a little better.

Benjamin Cox
Great description/level of help. Wish I could give +3
Bill K