TreeMap与HashMap不同点记录
排序
当有多条数据<Integer,Integer>存放到map中,而key值的大小是无序的,那么TreeMap会有一个自动排序的操作
例题
答案
public class Main{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
int size = sc.nextInt();
TreeMap<Integer,Integer> map = new TreeMap();
while(size>0){
int key = sc.nextInt();
int value = sc.nextInt();
if(map.containsKey(key)){
map.put(key,map.get(key)+value);
}else{
map.put(key,value);
}
size--;
}
Iterator iter = map.entrySet().iterator();
while (iter.hasNext()){
Map.Entry node = (Map.Entry) iter.next();
System.out.println(node.getKey()+" "+node.getValue());
}
}
}
这个时候用HashMap就不行,题目中要求按顺序输出,如果这里用HashMap的话顺序就会乱。