Skip to content
Advertisement

Collection cannot be converted to Object[]

Need help with a problem for a class! So I have created an array of names that gets passed to a method named runA in the class Proj04Runner. I need to create a TreeSet of these names to put them in naturally ascending order with no repeating values. However when I run my code, I get an error telling me that Collection cannot be converted to 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;
        }
}

Any help would be greatly appreciated! Thank you!

Advertisement

Answer

Problem

Let’s check the types:

  • myArray is type of Object[]
  • method runA takes one argument of type Object[] and returns Collection

The problem part is:

myArray = runner.runA(myArray);

Now we are supplying Object[] (myArray) to method runner.runA(), which is correct. On the other hand we are returning Collection and trying to assign it to variable of type Object[] (myArray), which is not correct.

Solution

Now you have many options to solve this type madness.

Obvious two are:

  • Make method runA return Object[] instead of Collection
    • e.g. return ref.stream().toArray()
  • Make myArray type of Collection instead of Object[]

Final notes

Do not use “raw” types

Instead of Collection, you say collection of what, e.g. collection of integers Collection<Integer> or collection of strings Collection<String>

int cnt is declared twice

Variable int cnt is declared two times in the same scope.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement