I'm just starting out in Java and looking for advice on a good way to store nested datasets. For example, I am interested in storing data on the population of the city, which can be accessed by viewing the city in a certain state. (Note: in the end, other data will be stored with each city, this is only the first attempt to start work.)
The current approach I'm using is to have a StateList object that contains a HashMap that stores state objects via a string key (i.e. HashMap <String, State>). Each state object contains its own HashMap of city objects, disconnected from the city name (i.e. HashMap <String, City>).
A shortened version of what I came up with looks like this:
//TestPopulation.java
public class TestPopulation {
public static void main(String [] args) {
StateList sl = new StateList();
State stateAl = sl.getState("AL");
if(stateAl != null) {
stateAl.addCity("Abbeville");
City cityAbbevilleAl = stateAl.getCity("Abbeville");
cityAbbevilleAl.setPopulation(2987);
System.out.print("The city has a pop of: ");
System.out.println(Integer.toString(cityAbbevilleAl.getPopulation()));
}
else {
System.out.println("That was an invalid state");
}
}
}
//StateList.java
import java.util.*;
public class StateList {
private HashMap<String, State> theStates = new HashMap<String, State>();
public StateList() {
String[] stateCodes = {"AL","AK","AZ","AR","CA","CO"};
for (String s : stateCodes) {
State newState = new State(s);
theStates.put(s, newState);
}
}
public State getState(String stateCode) {
if(theStates.containsKey(stateCode)) {
return theStates.get(stateCode);
}
else {
return null;
}
}
}
//State.java
import java.util.*;
public class State {
String stateCode;
HashMap<String, City> cities = new HashMap<String, City>();
public State(String newStateCode) {
System.out.println("Creating State: " + newStateCode);
stateCode = newStateCode;
}
public void addCity(String newCityName) {
City newCityObj = new City(newCityName);
cities.put(newCityName, newCityObj);
}
public City getCity(String cityName) {
if(cities.containsKey(cityName)) {
return cities.get(cityName);
}
else {
return null;
}
}
}
//City.java
public class City {
String cityName;
int cityPop;
public City(String newCityName) {
cityName = newCityName;
System.out.println("Created City: " + newCityName);
}
public void setPopulation(int newPop) {
cityPop = newPop;
}
public int getPopulation() {
return cityPop;
}
}
This works for me, but I wonder if there are any errors that I have not come across, or if there are alternative / better ways to do the same.
(PS I know that I need to add some more error checking, but right now I'm focusing on trying to find a good data structure.)
(NOTE: Edited to change setPop () and getPop () for setPopulation () and getPopulation (), respectively, to avoid confusion)