今天上午去参加面试的java题目, 这个该怎么做?
题目:
需要存储如下信息:
+Name+ + country+
John Canada
Bob USA
Tom USA
Alice Canada
Alan Canada
Peter UK
现在删除数据,让每个country只保留一个人,只保留第一次出现那个
则剩下:
+Name+ + country+
John Canada
Bob USA
Peter UK
请选择一种数据结构,并用java代码实现
简单一点,附上代码,如果有要求,可以实现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