有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java的集合是否实现了UnionFind算法?

我知道Wikipedia中的Union Find算法,并且可以找到它们的小实现,但是Java本身是否在其集合中使用了类似的算法?如果是这样的话,我更喜欢使用Java集,而不需要重新编码控制盘


共 (1) 个答案

  1. # 1 楼答案

    我同意第一个答案。此外,要在集合中查找元素,应该使用contains方法。其签名为:

    public boolean contains(Object o)
    
    Returns true if this set contains the specified element. More formally, returns true if and only if this set contains an element e such that (o==null ? e==null : o.equals(e)).
    
    Specified by:
        contains in interface Collection<E>
    
    Parameters:
        o - element whose presence in this set is to be tested. 
    Returns:
        true if this set contains the specified element. 
    Throws:
        ClassCastException - if the type of the specified element is incompatible with this set (optional). 
        NullPointerException - if the specified element is null and this set does not support null elements (optional).
    

    此外,这三种Set实现的实现方式也截然不同。哈希集将其元素存储在哈希表中,是性能最好的实现;然而,它不保证迭代的顺序。TreeSet将元素存储在一棵红黑树中,它根据元素的值对元素进行排序;它比HashSet慢很多。LinkedHashSet实现为一个哈希表,其中有一个链表贯穿其中,它根据元素插入集合的顺序(插入顺序)对元素进行排序。LinkedHashSet让其客户免受HashSet提供的未指明的、通常混乱的排序,成本仅略高