我刚刚开始学习Java,正在寻求关于存储嵌套数据的好方法的建议。例如,我希望存储可通过在给定州中查找城市来访问的城市人口数据。(注意:最终,每个城市都会存储其他数据,这只是入门的第一次尝试。)
目前我使用的方法是拥有一个StateList对象,其中包含一个HashMap,该HashMap通过字符串键(即HashMap)存储State对象。每个State对象都包含其自己的HashMap,以城市名称为键(i.e. HashMap)。
我想要实现的大致情况如下:
// TestPopulation.java
目前我使用的方法是拥有一个StateList对象,其中包含一个HashMap,该HashMap通过字符串键(即HashMap)存储State对象。每个State对象都包含其自己的HashMap,以城市名称为键(i.e. HashMap)。
我想要实现的大致情况如下:
// TestPopulation.java
public class TestPopulation {
public static void main(String [] args) {
// build the stateList Object
StateList sl = new StateList();
// get a test state
State stateAl = sl.getState("AL");
// make sure it's there.
if(stateAl != null) {
// add a city
stateAl.addCity("Abbeville");
// now grab the city
City cityAbbevilleAl = stateAl.getCity("Abbeville");
cityAbbevilleAl.setPopulation(2987);
System.out.print("The city has a pop of: ");
System.out.println(Integer.toString(cityAbbevilleAl.getPopulation()));
}
// otherwise, print an error
else {
System.out.println("That was an invalid state");
}
}
}
// StateList.java
import java.util.*;
public class StateList {
// define hash map to hold the states
private HashMap<String, State> theStates = new HashMap<String, State>();
// setup constructor that loads the states
public StateList() {
String[] stateCodes = {"AL","AK","AZ","AR","CA","CO"}; // etc...
for (String s : stateCodes) {
State newState = new State(s);
theStates.put(s, newState);
}
}
// define method for getting a state
public State getState(String stateCode) {
if(theStates.containsKey(stateCode)) {
return theStates.get(stateCode);
}
else {
return null;
}
}
}
// State.java
import java.util.*;
public class State {
// Setup the state code
String stateCode;
// HashMap for cities
HashMap<String, City> cities = new HashMap<String, City>();
// define the constructor
public State(String newStateCode) {
System.out.println("Creating State: " + newStateCode);
stateCode = newStateCode;
}
// define the method for adding a city
public void addCity(String newCityName) {
City newCityObj = new City(newCityName);
cities.put(newCityName, newCityObj);
}
// define the method for getting a city
public City getCity(String cityName) {
if(cities.containsKey(cityName)) {
return cities.get(cityName);
}
else {
return null;
}
}
}
// City.java
public class City {
// Define the instance vars
String cityName;
int cityPop;
// setup the constructor
public City(String newCityName) {
cityName = newCityName;
System.out.println("Created City: " + newCityName);
}
public void setPopulation(int newPop) {
cityPop = newPop;
}
public int getPopulation() {
return cityPop;
}
}
这对我有用,但我想知道是否有我没有遇到的问题,或者是否有其他/更好的方法来做同样的事情。
(附注:编辑后将setPop()和getPop()分别更改为setPopulation()和getPopulation()以避免混淆)
(顺便说一句,我知道需要添加更多的错误检查,但现在,我专注于尝试找出一个好的数据结构。)