package map.TreeMap;
import map.TreeMap.Sudent;
import java.util.Comparator;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeMap;
public class Demo01 {
public static void main(String[] args) {
//非自定义键
TreeMap<String,Integer> map=new TreeMap<>();
map.put("2陈碧忠",18);
map.put("3张全蛋",21);
map.put("2陈碧忠",19);
map.put("1王大拿",23);
map.put("4翠英",18);
map.remove("翠英");
System.out.println(map);
TreeMap<Integer,String> map1=new TreeMap<>();
map1.put(2,"陈碧忠");
map1.put(1,"张学友");
map1.put(9,"张国荣");
map1.put(5,"张家辉");
System.out.println(map1);
//遍历
for (Integer key:map1.keySet()
) {
System.out.println(key+" "+map1.get(key));
}
//尝试使用迭代器
System.out.println("尝试使用迭代器");
Set<Integer> set=map1.keySet();
Iterator it=set.iterator();
while(it.hasNext()){
Integer key=(Integer) it.next();
System.out.println(key+" "+map1.get(key));
}
//
/**
* 问题一:遍历结果是否有序
* 答:有序,在不使用自定义键时有序
* {1王大拿=23, 2陈碧忠=19, 3张全蛋=21, 4翠英=18}
* {1=张学友, 2=陈碧忠, 5=张家辉, 9=张国荣}
* 问题二:遍历结果是否有重复?
* 答:没有,在键相同时,没有输出重复的键,说明相同的键被覆盖掉了。
* 问题三:能否使用迭代器
* 答:能
* 问题四:使用自定义键需要重写方法比较方法吗
* 答:要,重写比较器(Comparator 实现compare)或合适自然排序方法( Comparable 实现compareTo)都可以
* 问题五:不使用自定义键时,为何不重写比较方法?
* 答:因为不是用自定义键,用的就是String和基本数据类型,而这些已经被默认重写过的
* */
//自定义key
System.out.println("自定义key");
TreeMap<Sudent, Integer> map2 = new TreeMap<>(new Comparator<Sudent>() {
@Override
public int compare(Sudent o1, Sudent o2) {
return 0;
}
});
map2.put(new Sudent(18,"陈碧忠"),1);
map2.put(new Sudent(19,"张家辉"),5);
map2.put(new Sudent(25,"刘德华"),1);
map2.put(new Sudent(18,"陈碧忠"),2);
Set<Sudent> students = map2.keySet();
Iterator<Sudent> it4 = students.iterator();
while(it4.hasNext()){
Sudent key2 = it4.next();
System.out.println(key2.getAge()+" "+key2.getName() +" "+map2.get(key2));
}
/**
* 自定义key
* 18 陈碧忠 2
* 19 张家辉 5
* 25 刘德华 1
* */
}
}
2020-08-30 我的关于TreeMap的一些疑问和理解
最新推荐文章于 2023-10-26 23:57:03 发布