简单的有序表介绍


前言


一、简单的有序表是什么?

二、两种形式

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;
		 }
	 }
// treeSet的key是非基础类型->Node类型
				nodeA = new Node(5);
				nodeB = new Node(3);
				nodeC = new Node(7);

				TreeSet<Node> treeSet = new TreeSet<>();
				// 以下的代码会报错,因为没有提供Node类型的比较器
				try {
    
    
					treeSet.add(nodeA);
					treeSet.add(nodeB);
					treeSet.add(nodeC);
				} catch (Exception e) {
    
    
					System.out.println("错误信息:" + e.getMessage());
				}

				treeSet = new TreeSet<>(new NodeComparator());
				// 以下的代码没问题,因为提供了Node类型的比较器
				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<>();
//void put(K key, V value):将一个(key,value)记录加入到表中,或者将key的记录
//或更新成value。
		treeMap1.put(7, "我是7");
		treeMap1.put(5, "我是5");
		treeMap1.put(4, "我是4");
		treeMap1.put(3, "我是3");
		treeMap1.put(9, "我是9");
		treeMap1.put(2, "我是2");
		//boolean containsKey(K key):询问是否有关于key的记录。
		System.out.println(treeMap1.containsKey(5));
		//V get(K key):根据给定的key,查询value并返回。
		System.out.println(treeMap1.get(5));
		//)K firstKey():返回所有键值的排序结果中,最左(最小)的那个。
		System.out.println(treeMap1.firstKey() + ", 我最小");
		//)K lastKey():返回所有键值的排序结果中,最右(最大)的那个
		System.out.println(treeMap1.lastKey() + ", 我最大");
		//K floorKey(K key):如果表中存入过key,返回key;否则返回所有键值的排序结果
		//中, key的前一个。
		System.out.println(treeMap1.floorKey(8) + ", 在表中所有<=8的数中,我离8最近");
		//K ceilingKey(K key):如果表中存入过key,返回key;
		//否则返回所有键值的排序结果中, key的后一个。
		System.out.println(treeMap1.ceilingKey(8) + ", 在表中所有>=8的数中,我离8最近");
		System.out.println(treeMap1.floorKey(7) + ", 在表中所有<=7的数中,我离7最近");

		System.out.println(treeMap1.ceilingKey(7) + ", 在表中所有>=7的数中,我离7最近");
		//void remove(K key):移除key的记录。
		treeMap1.remove(5);
		System.out.println(treeMap1.get(5) + ", 删了就没有了哦");

总结

Guess you like

Origin blog.csdn.net/weixin_51422230/article/details/121527282