前言
一、简单的有序表是什么?
二、两种形式
1.TreeSet
public class HashAndTree {
public static class Node{
public int value;
public Node next;
public Node(int val) {
value = val;
}
}
public static class NodeComparator implements Comparator<Node>{
@Override
public int compare(Node o1,Node o2) {
return o1.value - o2.value;
}
}
nodeA = new Node(5);
nodeB = new Node(3);
nodeC = new Node(7);
TreeSet<Node> treeSet = new TreeSet<>();
try {
treeSet.add(nodeA);
treeSet.add(nodeB);
treeSet.add(nodeC);
} catch (Exception e) {
System.out.println("错误信息:" + e.getMessage());
}
treeSet = new TreeSet<>(new NodeComparator());
try {
treeSet.add(nodeA);
treeSet.add(nodeB);
treeSet.add(nodeC);
System.out.println("这次节点都加入了");
} catch (Exception e) {
System.out.println(e.getMessage());
}
2.TreeMap和一些常用操作
public class HashAndTree {
public static class Node{
public int value;
public Node next;
public Node(int val) {
value = val;
}
}
public static class NodeComparator implements Comparator<Node>{
@Override
public int compare(Node o1,Node o2) {
return o1.value - o2.value;
}
}
TreeMap<Integer, String> treeMap1 = new TreeMap<>();
treeMap1.put(7, "我是7");
treeMap1.put(5, "我是5");
treeMap1.put(4, "我是4");
treeMap1.put(3, "我是3");
treeMap1.put(9, "我是9");
treeMap1.put(2, "我是2");
System.out.println(treeMap1.containsKey(5));
System.out.println(treeMap1.get(5));
System.out.println(treeMap1.firstKey() + ", 我最小");
System.out.println(treeMap1.lastKey() + ", 我最大");
System.out.println(treeMap1.floorKey(8) + ", 在表中所有<=8的数中,我离8最近");
System.out.println(treeMap1.ceilingKey(8) + ", 在表中所有>=8的数中,我离8最近");
System.out.println(treeMap1.floorKey(7) + ", 在表中所有<=7的数中,我离7最近");
System.out.println(treeMap1.ceilingKey(7) + ", 在表中所有>=7的数中,我离7最近");
treeMap1.remove(5);
System.out.println(treeMap1.get(5) + ", 删了就没有了哦");
总结