集合无法转换为 Object[]

Collection cannot be converted to Object[]

需要帮助解决 class 的问题!因此,我创建了一个名称数组,该名称数组被传递给 class Proj04Runner 中名为 运行A 的方法。我需要创建一个包含这些名称的 TreeSet 以将它们按自然升序排列且没有重复值。但是,当我 运行 我的代码时,我收到一条错误消息,告诉我 Collection 无法转换为 Object[].

import java.util.*;

class Proj04{
  static String[] names = 
  {"Don","don","Bill","bill","Ann","ann","Chris","chris"};
  
  static Object[] myArray = new String[8];
  
  public static void main(String args[]){

Proj04Runner runner = new Proj04Runner();

Random generator = null;
if(args.length != 0){
  System.out.println("seed = " + args[0] );
  generator = new Random(Long.parseLong(args[0]));
}else{

  long seed = new Date().getTime();
  System.out.println("seed = " + seed);
  generator = new Random(new Date().getTime());
}

System.out.print("Input:  ");
for(int cnt = 0;cnt < myArray.length;cnt++){
  int index = ((byte)generator.nextInt())/16;
  if(index < 0){
    index = -index;
  }
  if(index >= 8){
    index = 7;
  }
  myArray[cnt] = names[index];
  System.out.print(myArray[cnt] + " ");

System.out.println();

myArray = runner.runA(myArray);

System.out.print("Intermediate Results: ");
for(int cnt = 0; cnt<myArray.length;cnt++){
  System.out.print(myArray[cnt] + " ");

System.out.println();

}

        import java.util.*;
    
    class Proj04Runner{
        
        Object[] myArray;
        Collection ref;
    
        Proj04Runner(){
    
        public Collection runA(Object[] myArray){
            this.myArray = myArray;
            ref = new TreeSet();
            for(int ct = 0; ct < myArray.length; ct++){
                ref.add(String.valueOf(myArray[ct]));
            }
            return ref;
        }
}

如有任何帮助,我们将不胜感激!谢谢!

问题

让我们检查一下类型:

  • myArrayObject[]
  • 的类型
  • 方法runA接受一个Object[]类型的参数和returns Collection

问题部分是:

myArray = runner.runA(myArray);

现在我们向方法 runner.runA() 提供 Object[] (myArray),这是正确的。另一方面,我们正在 returning Collection 并试图将其分配给类型为 Object[] (myArray) 的变量,这是不正确的。

解决方案

现在你有很多选择来解决这种疯狂的类型。

明显的两个是:

  • 制作方法 runA return Object[] 而不是 Collection
    • 例如return ref.stream().toArray()
  • myArray 类型设为 Collection 而不是 Object[]

最后的笔记

不要使用“原始”类型

而不是 Collection,你说的是什么的集合,例如整数集合 Collection<Integer> 或字符串集合 Collection<String>

int cnt 声明了两次

变量int cnt在同一范围内声明了两次。