Reputation: 31
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.
Upvotes: 3
Views: 4006
Reputation: 31269
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.
Upvotes: 6