Make org.apache.commons.csv.CSVFormat.getHeader() public and make it return a clone.

git-svn-id: https://svn.apache.org/repos/asf/commons/proper/csv/trunk@1508585 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Gary D. Gregory 2013-07-30 19:32:40 +00:00
parent 69997467d4
commit 390800f288
3 changed files with 30 additions and 5 deletions

View File

@ -334,8 +334,13 @@ public class CSVFormat implements Serializable {
return escape;
}
String[] getHeader() {
return header;
/**
* Returns a copy of the header array.
*
* @return a copy of the header array
*/
public String[] getHeader() {
return header != null ? header.clone() : null;
}
/**

View File

@ -321,18 +321,19 @@ public class CSVParser implements Iterable<CSVRecord>, Closeable {
*/
private Map<String, Integer> initializeHeader() throws IOException {
Map<String, Integer> hdrMap = null;
if (this.format.getHeader() != null) {
String[] formatHeader = this.format.getHeader();
if (formatHeader != null) {
hdrMap = new LinkedHashMap<String, Integer>();
String[] header = null;
if (this.format.getHeader().length == 0) {
if (formatHeader.length == 0) {
// read the header from the first line of the file
final CSVRecord record = this.nextRecord();
if (record != null) {
header = record.values();
}
} else {
header = this.format.getHeader();
header = formatHeader;
}
// build the name to index mappings

View File

@ -31,6 +31,7 @@ import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Arrays;
import org.junit.Test;
@ -224,9 +225,27 @@ public class CSVFormatTest {
@Test
public void testWithHeader() throws Exception {
String[] header = new String[]{"one", "two", "three"};
// withHeader() makes a copy of the header array.
CSVFormat formatWithHeader = CSVFormat.DEFAULT.withHeader(header);
assertArrayEquals(header, formatWithHeader.getHeader());
assertNotSame(header, formatWithHeader.getHeader());
header[0] = "A";
header[1] = "B";
header[2] = "C";
assertFalse(Arrays.equals(formatWithHeader.getHeader(), header));
}
@Test
public void testGetHeader() throws Exception {
String[] header = new String[]{"one", "two", "three"};
CSVFormat formatWithHeader = CSVFormat.DEFAULT.withHeader(header);
// getHeader() makes a copy of the header array.
String[] headerCopy = formatWithHeader.getHeader();
headerCopy[0] = "A";
headerCopy[1] = "B";
headerCopy[2] = "C";
assertFalse(Arrays.equals(formatWithHeader.getHeader(), headerCopy));
assertNotSame(formatWithHeader.getHeader(), headerCopy);
}
@Test