3
public class Mass_Reading
{
   public static void main(String args[]) throws Exception
   {
     CSVReader reader = new CSVReader(new FileReader("Test_Graphs.csv"));

     List myEntries = reader.readAll();
     //System.out.println(myEntries);

     myEntries = new ArrayList<String>(myEntries);
     //System.out.println(myEntries);

     Object[] data = myEntries.toArray();
     System.out.println(data[0] + "");
     }
}

I'm trying to read a .csv file in and get the data into a workable data type. When read in it starts as a List of String Objects. In my code above I'm trying to get it to an array of Strings. My main hangup is getting the String Object to a String Literal. I keep getting the error java.lang.Object[] cannot be converted to java.lang.String[]. The code above compiles, but still does not achieve my goal. When it prints I still get a String Object. Thanks for any suggestions.

1
  • Can you paste the stacktrace and identify what line in your code is giving the error? Commented Feb 3, 2016 at 2:15

1 Answer 1

6

Use this code:

String[] data = myEntries.toArray(new String[myEntries.size()]);

The method that you call, myEntries.toArray(), always returns an Object[], which cannot be cast to a String[].

But there is an overloaded method that I call in the example above, in which you can pass in the right type of array as an argument. The toArray() method will then fill the passed in array if it is of sufficient size.

If it is not of sufficient size, it will create a new array of the right type (the same type as the argument that you passed in)

Because of that, you can also write:

String[] data = myEntries.toArray(new String[0]);

Some people prefer that, but I don't like the fact that this creates one wasted object, although in a real application this won't make a difference in performance.

Sign up to request clarification or add additional context in comments.

1 Comment

I don't have it on hand, but apparently in versions newer than Java 6, the zero array is actually faster.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.