使用场景
使用一致性hash时,如何找到一个hash值对应的临近节点,可以使用集合中获取数据的前驱和后继元素实现。
特性:
实现类:
1. 使用 NavigableSet(TreeSet 示例)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
import java.util.NavigableSet; import java.util.TreeSet;
public class NavigableSetExample { public static void main(String[] args) { NavigableSet<Integer> set = new TreeSet<>(); set.add(1); set.add(3); set.add(5); set.add(7);
// 获取给定元素的后继元素 Integer higher = set.higher(5); // 返回7 // 获取给定元素的前驱元素 Integer lower = set.lower(5); // 返回3
System.out.println("Higher than 5: " + higher); System.out.println("Lower than 5: " + lower); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import java.util.NavigableSet; import java.util.TreeSet;
public class CeilingExample { public static void main(String[] args) { NavigableSet<Integer> set = new TreeSet<>(); set.add(1); set.add(3); set.add(5); set.add(7);
// 获取大于等于给定元素的最小元素 Integer ceiling = set.ceiling(5); // 返回5
System.out.println("Ceiling of 5: " + ceiling); } } |
在这个例子中,当调用 set.ceiling(5); 时,将返回 5。这是因为 5 已经存在于集合中,所以根据 ceiling(E e) 方法的定义,它将返回大于等于给定元素的最小元素,在这个情况下,是 5 本身。
总结
在 Java 中,如果需要获取某个数据的下一个或上一个数据,可以使用实现了 NavigableSet 或 NavigableMap 接口的集合,如 TreeSet 和 TreeMap,或者其线程安全的版本 ConcurrentSkipListSet 和 ConcurrentSkipListMap。对于实现了 List 接口的集合,可以通过 ListIterator 来获取前后元素。选择合适的集合取决于数据的类型、集合的排序需求以及是否需要线程安全。