I need help to build a method that returns an array.

huangapple go评论87阅读模式
英文:

I need help to build a method that returns an array

问题

Sure, here's the translated code part:

所以我是Java的初学者我的老师要我编写一个返回包含两个元素的数组的方法
这是我写的代码
```java
public int[] getXY() {
    int[] a = new int[2];
    a[0] = getX();
    a[1] = getY();
    return a;
}

getX和getY分别返回this.x和this.y。
显然,这个方法返回数组的引用,而不是数组本身的元素,这不是我想要的,但我没有想法。
他明确指出方法必须返回一个包含两个元素的数组,所以我没有使用String。
有什么建议吗?



<details>
<summary>英文:</summary>

So, i&#39;m a beginner in Java, and my teacher wants me to build a method that returns an Array of two elements.
This is what i&#39;ve made

public int[] getXY() {
int[] a = new int[2];
a[0]=getX();
a[1]=getY();
return a;
}

getX and getY returns this.x and this.y respectively.
So obviously this method returns the reference to the array, not the elements of the array itself, which is what i want to do, but i&#39;ve no ideas.
He made it clear that the method has to return an Array of two elements, so that&#39;s why i didn&#39;t make it with String.
Any suggestions?

</details>


# 答案1
**得分**: 2

你所得到的是正确的解决方案。在Java中,你无法获得"数组本身"。你所拥有的只是对数组的引用。

这听起来像是一个简单的交流误解。由于你只能拥有对数组(或一般情况下对任何对象)的引用,而不是数组本身,人们有时会使用不太准确的措辞,说"这个方法返回一个数组",实际上他们指的是"这个方法返回对一个数组的引用"。

<details>
<summary>英文:</summary>

What you have got is the correct solution. In Java, you cannot get the &quot;array itself.&quot; All you can have is a reference to the array.

This sounds like a simple miscommunication. Since you can only have a reference to an array (or to any object in general) - never the array itself, people sometimes use loose language and say *&quot;this method returns an array&quot;* when they mean *&quot;this method returns a reference to an array&quot;*.

</details>



huangapple
  • 本文由 发表于 2020年8月14日 03:02:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/63401647.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定