什么参数类型适用于Java?在Collection和Object数组之间如何转换?

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

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&lt;Type&gt;. Also, in Proj04Runner it should be

Collection runA(Object[] myArray) { // &lt;-- takes an `Object[]`

Finally, you haven't shown much code. But you are running Proj04 (not Proj04Runner).

huangapple
  • 本文由 发表于 2020年10月25日 10:44:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/64519833.html
匿名

发表评论

匿名网友

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

确定