用Java map和list集合写一个省市区的增删改查
时间: 2023-05-17 07:02:40 浏览: 107
非常好的问题!以下是一个使用Java map和list集合实现省市区增删改查的示例代码:
```
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ProvinceCityArea {
private Map<String, List<String>> provinceCityMap;
public ProvinceCityArea() {
provinceCityMap = new HashMap<>();
}
public void addProvince(String province) {
provinceCityMap.put(province, new ArrayList<>());
}
public void addCity(String province, String city) {
List<String> cities = provinceCityMap.get(province);
if (cities != null) {
cities.add(city);
}
}
public void addArea(String province, String city, String area) {
List<String> cities = provinceCityMap.get(province);
if (cities != null) {
int index = cities.indexOf(city);
if (index >= 0) {
List<String> areas = new ArrayList<>(cities.subList(index + 1, cities.size()));
areas.add(area);
cities.subList(index + 1, cities.size()).clear();
cities.addAll(areas);
}
}
}
public void removeProvince(String province) {
provinceCityMap.remove(province);
}
public void removeCity(String province, String city) {
List<String> cities = provinceCityMap.get(province);
if (cities != null) {
cities.remove(city);
}
}
public void removeArea(String province, String city, String area) {
List<String> cities = provinceCityMap.get(province);
if (cities != null) {
int index = cities.indexOf(city);
if (index >= 0) {
List<String> areas = new ArrayList<>(cities.subList(index + 1, cities.size()));
areas.remove(area);
cities.subList(index + 1, cities.size()).clear();
cities.addAll(areas);
}
}
}
public List<String> getCities(String province) {
return provinceCityMap.get(province);
}
public List<String> getAreas(String province, String city) {
List<String> cities = provinceCityMap.get(province);
if (cities != null) {
int index = cities.indexOf(city);
if (index >= 0) {
return cities.subList(index + 1, cities.size());
}
}
return null;
}
}
```
这个类使用了一个Map来存储省份和城市的关系,每个省份对应一个List,其中存储了该省份下的所有城市。每个城市也对应一个List,其中存储了该城市下的所有区域。可以使用addProvince、addCity、addArea、removeProvince、removeCity、removeArea、getCities和getAreas方法来增加、删除和查询省份、城市和区域。
阅读全文