心法领悟059:掌握各种Map集合。
Map集合的具体实现有很多,应该根据需要来选择。其中HashMap是最常用的映射集合,它只允许一条记录的键为null,但是却不限制集合中值为null的数量。HashTable实现了一个映射,它不允许任何键值为空,TreeMap集合将对集合中的键值排序,默认排序方式为升序。
public static Map<String,String[]> model=new LinkedHashMap();
static{
model.put("北京", new String[]{"北京"});
model.put("上海", new String[]{"上海"});
model.put("天津", new String[]{"天津"});
model.put("重庆", new String[]{"重庆"});
model.put("黑龙江", new String[]{"哈尔滨","齐齐哈尔","牡丹江","大庆","伊春","双鸭山","鹤岗","鸡西","佳木斯","七台河","黑河","绥化","大兴安岭"});
model.put("吉林", new String[]{"长春","延边","吉林","白山","白城","四平","松原","辽源","大安","通化"});
model.put("辽宁", new String[]{"沈阳","大连","葫芦岛","旅顺","本溪","抚顺","铁岭","辽阳","营口","阜新","朝阳","锦州","丹东","鞍山"});
//.....
public Object[] getProvince() {
Map<String, String[]> map = CityMap.model;// 获取省份信息保存到Map中
Set<String> set = map.keySet(); // 获取Map集合中的键,并以Set集合返回
Object[] province = set.toArray(); // 转换为数组
return province; // 返回获取的省份信息
}
public String[] getCity(String selectProvince) {
Map<String, String[]> map = CityMap.model; // 获取省份信息保存到Map中
String[] arrCity = map.get(selectProvince); // 获取指定键的值
return arrCity; // 返回获取的市/县
}
private void itemChange() {
String selectProvince = (String) comboBox.getSelectedItem();
cityComboBox.removeAllItems(); // 清空市/县列表
String[] arrCity = getCity(selectProvince); // 获取市/县
cityComboBox.setModel(new DefaultComboBoxModel(arrCity)); // 重新添加市/县列表的值
}