英文:
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'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'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've no ideas.
He made it clear that the method has to return an Array of two elements, so that's why i didn'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 "array itself." 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 *"this method returns an array"* when they mean *"this method returns a reference to an array"*.
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论