TreeMap和HashMap都是一个具体的集合类,都是以键值对的形式进行元素的存储.存储的类型必须是引用数据类型,基本数据类型在存储过程中会有一个自动装箱的操作
TreeMap:是有序的 会对元素进行自动排序 默认是采取自然排序的方式
HashMap:是无序的,它的排序方式依照元素对应的哈希值
代码演示:
这里以统计一个字符串每个字符出现的次数为例
TreeMap:
import java.util.*;
//录入一串字符串,输出该字符串中每个字符出现的次数 要求按照字符在字典序中的位置进行输出
public class test {
public static void main(String[] args) {
String s =new Scanner(System.in).next();
TreeMap<Character,Integer>map=new TreeMap<>();
//循环遍历字符串
for(int i =0;i<s.length();i++){
if(map.containsKey(s.charAt(i))){//如果遍历的字符在map集合中存在 那么对应的值就加一
map.put(s.charAt(i),map.get(s.charAt(i))+1);
}
else{
map.put(s.charAt(i),1);
}
}
Set<Map.Entry<Character,Integer>>set=map.entrySet();
for(Map.Entry<Character,Integer>x:set){
System.out.println(x.getKey()+"\t"+x.getValue());
}
}
}
代码运行效果如下图
HashMap:
import java.util.*;
//录入一串字符串,输出该字符串中每个字符出现的次数 要求按照字符在字典序中的位置进行输出
public class test {
public static void main(String[] args) {
String s =new Scanner(System.in).next();
HashMap<Character,Integer>map=new HashMap<>();
//循环遍历字符串
for(int i =0;i<s.length();i++){
if(map.containsKey(s.charAt(i))){//如果遍历的字符在map集合中存在 那么对应的值就加一
map.put(s.charAt(i),map.get(s.charAt(i))+1);
}
else{
map.put(s.charAt(i),1);
}
}
Set<Map.Entry<Character,Integer>>set=map.entrySet();
for(Map.Entry<Character,Integer>x:set){
System.out.println(x.getKey()+"\t"+x.getValue());
}
}
}
代码运行效果如下图
如上演示所示,TreeMap集合默认按照键元素进行自然排序,而HashMap则不具备该特性,它依照元素的哈希值进行排序,所以展示出来的结果是乱序