Skip to content

Commit f881372

Browse files
committed
Validate that headers do not contain duplicates.
git-svn-id: https://svn.apache.org/repos/asf/commons/proper/csv/trunk@1508618 13f79535-47bb-0310-9956-ffa450edef68
1 parent 3320c53 commit f881372

2 files changed

Lines changed: 16 additions & 1 deletion

File tree

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

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,11 +17,11 @@
1717

1818
package org.apache.commons.csv;
1919

20+
import static org.apache.commons.csv.Constants.BACKSLASH;
2021
import static org.apache.commons.csv.Constants.COMMA;
2122
import static org.apache.commons.csv.Constants.CR;
2223
import static org.apache.commons.csv.Constants.CRLF;
2324
import static org.apache.commons.csv.Constants.DOUBLE_QUOTE_CHAR;
24-
import static org.apache.commons.csv.Constants.BACKSLASH;
2525
import static org.apache.commons.csv.Constants.LF;
2626
import static org.apache.commons.csv.Constants.TAB;
2727

@@ -30,6 +30,8 @@
3030
import java.io.Serializable;
3131
import java.io.StringWriter;
3232
import java.util.Arrays;
33+
import java.util.HashSet;
34+
import java.util.Set;
3335

3436
/**
3537
* Specifies the format of a CSV file and parses input.
@@ -530,6 +532,14 @@ void validate() throws IllegalStateException {
530532
if (escape == null && quotePolicy == Quote.NONE) {
531533
throw new IllegalStateException("No quotes mode set but no escape character is set");
532534
}
535+
536+
if (header != null) {
537+
Set<String> set = new HashSet<String>(header.length);
538+
set.addAll(Arrays.asList(header));
539+
if (set.size() != header.length) {
540+
throw new IllegalStateException("The header contains duplicate names: " + Arrays.toString(header));
541+
}
542+
}
533543
}
534544

535545
/**

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

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,11 @@ public void testDelimiterSameAsEscapeThrowsException() {
5757
CSVFormat.DEFAULT.withDelimiter('!').withEscape('!').validate();
5858
}
5959

60+
@Test(expected = IllegalStateException.class)
61+
public void testDuplicateHeaderElements() {
62+
CSVFormat.DEFAULT.withHeader("A", "A").validate();
63+
}
64+
6065
@Test
6166
public void testEquals() {
6267
final CSVFormat right = CSVFormat.DEFAULT;

0 commit comments

Comments
 (0)