目录
0、定义
java的TreeSet是使用TreeMap实现的,只是TreeMap可以存储“关键字/值”对。树映射保证节点是按照节点中的关键字升序或降序排列的。(TreeSet仅使用了TreeMap的关键字进行存储。)
TreeMap升序降序与key实现的comparable接口方法编写有关。(Integer等包装类是升序,且无法存储相同的值,会覆盖。)
1、示例代码
package xyz.jangle.base;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;
/**
* 树映射 TreeMap demo
*
* @author Administrator
*
*/
public class Example13_9 {
public static void main(String[] args) {
Student3 s1 = new Student3("A",60);
Student3 s2 = new Student3("B",80);
Student3 s3 = new Student3("C",70);
Student3 s4 = new Student3("D",90);
Map<Integer,Student3> map = new TreeMap<Integer,Student3>();
map.put(s1.getMath(), s1);
map.put(s2.getMath(), s2);
map.put(s3.getMath(), s3);
map.put(s4.getMath(), s4);
for(Integer key:map.keySet()) {
System.out.println(map.get(key).getName()+","+map.get(key).getMath());
}
System.out.println("--------------");
Iterator<Student3> iterator = map.values().iterator();
while(iterator.hasNext()) {
Student3 next = iterator.next();
System.out.println(next.getName()+","+next.getMath());
}
}
}
class Student3 {
private String name;
private Integer math;
public Student3(String name, Integer math) {
super();
this.name = name;
this.math = math;
}
public String getName() {
return name;
}
public Integer getMath() {
return math;
}
}