简单一点,附上代码,如果有要求,可以实现map接口,不过得改写一堆方法
考点:
1,面向对象的Java编程,数据结构一般要写一个class
2,国家名不能重复,要考虑HasMap,把国家名作为一个key
3,先国家名输入者,后面不能update,考虑在改写put方法,检验是否存在重复。
import java.util.HashMap;
import java.util.Map.Entry;
public class MyMap {
protected String name;
protected String country;
protected HashMap<String, String> map = new HashMap<String, String>();
public MyMap() {}
public void put(String name, String country) {
if(!map.containsKey(country)) {
map.put(country, name);
}
}
public String toString() {
String s = "";
for(Entry<String, String> e : map.entrySet()) {
s += e.getValue() + " " + e.getKey() + "n";
}
return s;
}
public static void main(String[] args) {
MyMap myMap = new MyMap();
myMap.put("John", "Canada");
myMap.put("Bob", "USA");
myMap.put("Tom", "USA");
myMap.put("Alice", "Canada");
myMap.put("Alan", "Canada");
myMap.put("Peter", "UK");
myMap.put("Peter", "China");
System.out.println(myMap.toString());
}
}
输出:
John Canada
Bob USA
Peter UK
Peter China
1,面向对象的Java编程,数据结构一般要写一个class
2,国家名不能重复,要考虑HasMap,把国家名作为一个key
3,先国家名输入者,后面不能update,考虑在改写put方法,检验是否存在重复。
import java.util.HashMap;
import java.util.Map.Entry;
public class MyMap {
protected String name;
protected String country;
protected HashMap<String, String> map = new HashMap<String, String>();
public MyMap() {}
public void put(String name, String country) {
if(!map.containsKey(country)) {
map.put(country, name);
}
}
public String toString() {
String s = "";
for(Entry<String, String> e : map.entrySet()) {
s += e.getValue() + " " + e.getKey() + "n";
}
return s;
}
public static void main(String[] args) {
MyMap myMap = new MyMap();
myMap.put("John", "Canada");
myMap.put("Bob", "USA");
myMap.put("Tom", "USA");
myMap.put("Alice", "Canada");
myMap.put("Alan", "Canada");
myMap.put("Peter", "UK");
myMap.put("Peter", "China");
System.out.println(myMap.toString());
}
}
输出:
John Canada
Bob USA
Peter UK
Peter China