引出:从TreeMap的put方法中来看
在往TreeMao集合里添加元素的时候,会进行比较添加元素的key值,这时就会用到比较器,在源码中有两种比较器。
[1] key值自己是系统定义好的,像Integer、String等,那么Integer或String本身自带compareTo方法,然后来进行比较
从代码中看
public class Test01 { public static void main(String[] args) { //这里的key是String它自身带了比较器即比较的方法,因此不需要自己来弄比较器 TreeMaptreeMap = new TreeMap<>(); treeMap.put("Tom",101); treeMap.put("Confidence",101); treeMap.put("Excellent",101); treeMap.put("Apple",101); treeMap.put("Google",101); System.out.println(treeMap); } }
(2)自定义类实现Comparator
从代码来看方法一:
public class Student { //为了节约空间,这个类在这里只显示了它的属性 private int Std; private String name; } //自己定义一个比较类名字为CompareName class CompareName implements Comparator{ //这个类实现了Comparator接口,它是一个外部比较器的接口, //如下面方法所示,这个compare方法用来比较传进参数的两个Student对象的name属性 @Override public int compare(Student o1, Student o2) { return o1.getName().compareTo(o2.getName()); } } public class Test01 { public static void main(String[] args) { //创建比较类的对象 CompareName cn = new CompareName(); //在创建对象时,传入比较类的对象,因为到时候要调用这个比较类对象里的比较方法 TreeMap map = new TreeMap<>(cn); map.put((new Student(105,"Tom")),103); map.put((new Student(103,"Cat")),103); map.put((new Student(102,"Excellent")),104); map.put((new Student(108,"Legend")),106); map.put((new Student(108,"Apple")),106); System.out.println(map); } }
可能会有个疑问,为啥在创建TreeMap集合对象时可以传进自己定义那个类的对象呢?
下面我们从源码来看:
方法二:其实跟方法一差不多 只不过是在定义 比较类的时候直接在创建TreeMap集合对象那里进行 *** 作,如下面代码所示:
public class Student { //为了节约空间,这个类在这里只显示了它的属性 private int Std; private String name; } import java.util.Comparator; import java.util.TreeMap; public class Test01 { public static void main(String[] args) { TreeMapmap = new TreeMap<>(new Comparator () { @Override public int compare(Student o1, Student o2) { return o1.getName().compareTo(o2.getName()); } }); map.put((new Student(105,"Tom")),103); map.put((new Student(103,"Cat")),103); map.put((new Student(102,"Excellent")),104); map.put((new Student(108,"Legend")),106); map.put((new Student(108,"Apple")),106); System.out.println(map); } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)