Java:从定义位置的数组中获取值 [英] Java: getting a value from an array from a defined location

查看:45
本文介绍了Java:从定义位置的数组中获取值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数字数组,想从索引"位置检索其中一个值.我看过 Java 文档 http://java.sun.com/j2se/1.5.0/docs/api/java/lang/reflect/Array.html 但我的代码仍未编译.

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.

这是我的方法:

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 !

推荐答案

在 Java 中,数组索引由方括号表示.你可以像这样替换你的 get(vertices, index) 调用:

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

  vertex = vertices[index];

在查看您的代码时,您似乎来自一种为此类操作定义全局 get() 函数的语言.请注意,在 Java 中,没有全局函数.您创建的每个类都定义了自己的函数,并且假定在其前面没有对象或类的任何函数调用都是在本地类中定义的.

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.

因此,只有在此类上定义该函数时,您对 get(Point[], int) 的调用才能起作用:

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);

现在,请注意,我认为您不应该这样做!我只是觉得它可以帮助你更好地理解 Java.

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.

这篇关于Java:从定义位置的数组中获取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆