Skip to content

Commit ce4e727

Browse files
committed
CSV-112: HeaderMap is inconsistent when it is parsed from an input with duplicate columns names. Reported by Romain Gossé
git-svn-id: https://svn.apache.org/repos/asf/commons/proper/csv/trunk@1592371 13f79535-47bb-0310-9956-ffa450edef68
1 parent c84328e commit ce4e727

2 files changed

Lines changed: 9 additions & 0 deletions

File tree

src/main/java/org/apache/commons/csv/CSVParser.java

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@
2929
import java.net.URL;
3030
import java.nio.charset.Charset;
3131
import java.util.ArrayList;
32+
import java.util.Arrays;
3233
import java.util.Collection;
3334
import java.util.Iterator;
3435
import java.util.LinkedHashMap;
@@ -368,6 +369,9 @@ private Map<String, Integer> initializeHeader() throws IOException {
368369
// build the name to index mappings
369370
if (header != null) {
370371
for (int i = 0; i < header.length; i++) {
372+
if (hdrMap.containsKey(header[i])) {
373+
throw new IllegalStateException("The header contains duplicate names: " + Arrays.toString(header));
374+
}
371375
hdrMap.put(header[i], Integer.valueOf(i));
372376
}
373377
}

src/test/java/org/apache/commons/csv/CSVParserTest.java

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -492,6 +492,11 @@ public void testGetHeaderMap() throws Exception {
492492
parser.close();
493493
}
494494

495+
@Test(expected = IllegalStateException.class)
496+
public void testDuplicateHeaderEntries() throws Exception {
497+
CSVParser.parse("a,b,a\n1,2,3\nx,y,z", CSVFormat.DEFAULT.withHeader(new String[]{}));
498+
}
499+
495500
@Test
496501
public void testGetLine() throws IOException {
497502
final CSVParser parser = CSVParser.parse(CSV_INPUT, CSVFormat.DEFAULT.withIgnoreSurroundingSpaces(true));

0 commit comments

Comments
 (0)