diff --git a/src/main/java/org/apache/commons/csv/CSVFormat.java b/src/main/java/org/apache/commons/csv/CSVFormat.java index 7e85e303..2ac58957 100644 --- a/src/main/java/org/apache/commons/csv/CSVFormat.java +++ b/src/main/java/org/apache/commons/csv/CSVFormat.java @@ -17,11 +17,11 @@ package org.apache.commons.csv; +import static org.apache.commons.csv.Constants.BACKSLASH; import static org.apache.commons.csv.Constants.COMMA; import static org.apache.commons.csv.Constants.CR; import static org.apache.commons.csv.Constants.CRLF; import static org.apache.commons.csv.Constants.DOUBLE_QUOTE_CHAR; -import static org.apache.commons.csv.Constants.BACKSLASH; import static org.apache.commons.csv.Constants.LF; import static org.apache.commons.csv.Constants.TAB; @@ -30,6 +30,8 @@ import java.io.Reader; import java.io.Serializable; import java.io.StringWriter; import java.util.Arrays; +import java.util.HashSet; +import java.util.Set; /** * Specifies the format of a CSV file and parses input. @@ -530,6 +532,14 @@ public class CSVFormat implements Serializable { if (escape == null && quotePolicy == Quote.NONE) { throw new IllegalStateException("No quotes mode set but no escape character is set"); } + + if (header != null) { + Set set = new HashSet(header.length); + set.addAll(Arrays.asList(header)); + if (set.size() != header.length) { + throw new IllegalStateException("The header contains duplicate names: " + Arrays.toString(header)); + } + } } /** diff --git a/src/test/java/org/apache/commons/csv/CSVFormatTest.java b/src/test/java/org/apache/commons/csv/CSVFormatTest.java index f97409dd..0701ab60 100644 --- a/src/test/java/org/apache/commons/csv/CSVFormatTest.java +++ b/src/test/java/org/apache/commons/csv/CSVFormatTest.java @@ -57,6 +57,11 @@ public class CSVFormatTest { CSVFormat.DEFAULT.withDelimiter('!').withEscape('!').validate(); } + @Test(expected = IllegalStateException.class) + public void testDuplicateHeaderElements() { + CSVFormat.DEFAULT.withHeader("A", "A").validate(); + } + @Test public void testEquals() { final CSVFormat right = CSVFormat.DEFAULT;