从方法的返回值返回数组的索引

时间:2018-06-15 11:08:23

标签: java oop

我的一个课程中有这个方法:

public int[] getCurrentGridPosition()
{        
    return new int[]{currentGridPosX, currentGridPosY};
}

Java是否允许使用以下内容:

int x, y;
x = getCurrentGridPosition()[0];
y = getCurrentGridPosition()[1];

如果是,怎么样?如果不是,为什么?

2 个答案:

答案 0 :(得分:2)

  

Java是否允许使用以下内容:

是的,这段代码没有任何 错误。这里有一个完整的程序,用你的代码证明它有效:

class Main{
  private int currentGridPosX = 5, 
              currentGridPosY = 10;

  public static void main(String[] a){
    Main m = new Main();
    m.test();
  }

  private void test(){
    int x, y;
    x = getCurrentGridPosition()[0];
    y = getCurrentGridPosition()[1];
    System.out.print("x: "+x+"; y: "+y);
  }

  public int[] getCurrentGridPosition()
  {        
    return new int[]{currentGridPosX, currentGridPosY};
  }
}

Try it online.

:编译/运行时明智没有错。在最佳实践方面,当然有待改进的地方。

  

如果是,怎么样?

x = getCurrentGridPosition()[0];将调用该方法并给出一个数组作为结果,然后将获取索引0的元素,并将其保存在字段x中。
y = getCurrentGridPosition()[1];将再次调用该方法并给出一个数组作为结果,然后将获取索引为1的元素,并将其保存在字段y中。

因此,在几乎所有情况下,最好只调用一次方法并将结果数组保存在变量中,然后才能在索引01访问其元素:

int[] gridPositions = getCurrentGridPosition(); // The method is only called once now
int x = gridPositions[0],
    y = gridPositions[1];
System.out.print("x: "+x+"; y: "+y);

答案 1 :(得分:0)

为什么不用更多的代码行呢? 例如,您可以像这样访问返回的数组:

int x, y;
int[] myArray = getCurrentGridPosition();
x = myArray[0];
y = myArray[1];
System.out.println("x: " + String.valueOf(x) + ", y: " + String.valueOf(y));
相关问题