I have a strange situation with my HashMaps. While iterating through the keySet() of the HashMap I've got duplicated values. And while trying to get a value I've got NULL.
Here is my HashMap implementation:
import java.util.ArrayList;
import java.util.HashMap;
public class StreetsMap extends HashMap<String, ArrayList<String[]>> {
public void put(String key, String[] data) {
ArrayList<String[]> current = get(key);
if (current == null) {
current = new ArrayList<String[]>();
super.put(key, current);
}
current.add(data);
}
}
While reading lines from a CSV file I'm filling a HashMap with values.
I have something like this in CSV (original list is much longer):
Location_Code, Street_Name, Start, End, OddEven
01001, JustAStreet ST, 1, 11, odd
01001, JustAStreet ST, 17, 47, odd
... more of this
01001, JustAStreet ST, 2, 30, even
01001, JustAStreet ST, 40, 80, even
01001, AnotherStreet ST, 3, 27, odd
01001, AnotherStreet ST, 9, 51, odd
... and even more
01001, AnotherStreet ST, 0, 50, even
01001, AnotherStreet ST, 2, 14, even
01001, AnotherStreet ST, 0, 100, even
I'm splitting a line by comma, trimming values and filling HashMap with data:
String[] lines = inputText.split("\n");
StreetsMap streetsData = new StreetsMap(); //
for (String line : lines) {
String[] newLine = line.split(",");
String[] streetData = new String[4];
streetData[0] = newLine[0].trim(); // Location code
streetData[1] = newLine[2].trim(); // Start
streetData[2] = newLine[3].trim(); // End
streetData[3] = newLine[4].trim(); // OddEven
streetsData.put(newLine[1].trim(), streetData);
And the problem starts right here. If I iterate through keySet():
for (String name : streetsData.keySet()) {
System.out.println(name);
}
I've got something like:
- JustAStreet
- AnotherStreet
- AnotherStreet
- JustAStreet
- JustAStreet
When I try to access data with .get(key) method during iteration through HashMap sometimes I get null. So I'm loosing values. :(
My question is: how can it be real having a duplicated key in a HashMap? What I'm doing wrong.
UPD: Keys are unique. Found the problem in another class.