英文:
What parameter type to use in Java/converting between Collection and Object array?
问题
我在做一个学校作业,需要将一个数组传递给一个方法。数组的声明如下:
static Object[] myArray = new String[8];
在这里调用它(Proj04Runner 是我们被要求为作业创建的类):
Proj04Runner runner = new Proj04Runner();
myArray = runner.runA(myArray);
我试图在 Proj04Runner 类中创建一个名为 runA 的方法,但是我一直在收到错误消息。我尝试过:
Collection runA(Object[] myArray){
和
Collection runA(Collection myArray){
但两次都收到了错误消息。错误消息分别是:
Proj04.java:60: error: incompatible types: Collection cannot be converted to Object[]
Proj04.java:60: error: incompatible types: Object[] cannot be converted to Collection
我做错了什么?
英文:
I'm doing a school assignment where I need to pass an array into a method. The array declaration is as follows:
static Object[] myArray = new String[8];
It is called here (Proj04Runner is the class we are asked to create for the assignment):
Proj04Runner runner = new Proj04Runner();
myArray = runner.runA(myArray);
I tried to make a method in my Proj04Runner class called runA, but I keep getting error messages. I have tried:
Collection runA(Object[] myArray){
and
Collection runA(Collection myArray){
but get error messages both times. The error messages are, respectively:
Proj04.java:60: error: incompatible types: Collection cannot be converted to Object[]
Proj04.java:60: error: incompatible types: Object[] cannot be converted to Collection
What am I doing wrong?
答案1
得分: 1
你正在尝试将结果赋回给myArray
。你不能这样做,因为myArray
的类型是static Object[]
。你可以通过定义一个新变量来保存结果来修复这个问题。像这样:
Collection myCollection = runner.runA(myArray);
注意:在Java中使用原始类型(rawtypes)是不好的做法。Collection
是一个泛型类型。它应该是某种Collection<Type>
。另外,在Proj04Runner
中应该是这样的:
Collection runA(Object[] myArray) { // <-- 接受一个 `Object[]`
最后,你没有展示太多的代码。但是你在运行的是Proj04
(而不是Proj04Runner
)。
英文:
You are trying to assign the result back to myArray
. You can't do that. Because the type of myArray
is static Object[]
. You fix it by defining a new variable to hold the result. Like,
Collection myCollection = runner.runA(myArray);
Note: It's a bad idea to use rawtypes in Java. Collection
is a generic type. It should be some kind of Collection<Type>
. Also, in Proj04Runner
it should be
Collection runA(Object[] myArray) { // <-- takes an `Object[]`
Finally, you haven't shown much code. But you are running Proj04
(not Proj04Runner
).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论