0
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Arrays;
 
public class Main{
  public static void main(String[] args) throws IOException{
    BufferedReader reader = null; 
    ArrayList<String> lines = new ArrayList<String>();
    try{
      reader = new BufferedReader(new FileReader("Numbers.txt"));
      String currentLine = reader.readLine();
    }
    catch (IOException e) {
    System.out.println("ERROR: WRONG FILE " + e.toString());
    }
    String currentLine = reader.readLine();
    while (currentLine != null){
      lines.add(currentLine);
      currentLine = reader.readLine();
    Collections.sort(lines);
    ArrayList[] linesSorted = lines.toArray(new ArrayList[lines.size()]);
    System.out.println("Sorted Array: " + Arrays.toString(linesSorted));
    }
  }
}

When I enter this Code, which is meant to Read a list of Words from another File, Turn it into an Array, and then Sort said Array, an Error Message Pops up saying

Exception in thread "main" java.lang.ArrayStoreException: arraycopy: element type mismatch: can not cast one of the elements of java.lang.Object[] to the type of the destination array, java.util.ArrayList
    at java.base/java.lang.System.arraycopy(Native Method)
    at java.base/java.util.ArrayList.toArray(ArrayList.java:433)
    at Main.main(Main.java:24)

I'm not too sure what this Error Message Means, or how I can fix it. Help! I am very new to Computer coding, so my knowledge about the topic is not great.

Andy
  • 11

1 Answers1

-1

You have:

ArrayList<String> lines = new ArrayList<String>();

And you do:

ArrayList[] linesSorted = lines.toArray(new ArrayList[lines.size()]);

The expected type of array for toArray() is either:

  • toArray(new String[0]);
  • toArray(new Object[0]);

You can not use new ArrayList[lines.size()] because the ArrayList is storing String (array type should be String[]) and you pass a ArrayList[].

The compiler could probably have tell you about this either as a warning, either as an error.

NoDataFound
  • 11,381
  • 33
  • 59