Univocity - how to properly write a row without a primitive array

363 Views Asked by At

I am using this:

List<String> row = new ArrayList<String>();
row.add("value 1");
row.add("value 2");
writer.writeRow(row);

Which outputs what's essentially an ArrayList toString() value:

"[value1, value2]"

How to obtain the following?

"value1, value2"
2

There are 2 best solutions below

0
On

To make matters worse, headers are written correctly from a List:

List<String> headers = new ArrayList<String>();
headers.add("date");
writer.writeHeaders(headers);

I looked at some of their examples (specifically com.univocity.parsers.examples.CsvWriterExamples) and saw the output was correct.

So I got to this:

String[] rowData = new String[2];
rowData[0] = "value 1";
rowData[1] = "value 2";
mWriter.writeRow(rowData);

Which also produced a correct output.

Since there's also an overloaded method with a (Object... object) parameter, my guess is Java uses that one.

My issue can be fixed by casting the List to a Collection.

mWriter.writeRow((Collection)row);

I know this is pretty much how Java works, but I think most people would prefer avoiding primitives if extreme performance is not needed, so this should work out of the box - possibly with a different signature method.

0
On

Author of the library here. I've just updated it to fix this annoyance - it was essentially a rookie mistake with generics.

As you can see in this commit, the method signature was:

public final void writeRow(Collection<Object> row)

As you were passing a List<String> it wasn't matching the proper method signature and was going to another one that accepts Object varargs.

I've updated the code to have this signature as the collection type doesn't matter at all:

public final void writeRow(Collection<?> row)

If you update to version 2.6.0 that code you posted originally will produce the correct results, no need to cast anything.

Sorry for the trouble.