app/src/main/java/org/jgrapht/alg/util/UnionFind.java
public void union(T element1, T element2)
    {
        if (!parentMap.containsKey(element1)
            || !parentMap.containsKey(element2))
        {
            throw new IllegalArgumentException(
                "elements must be contained in given set");
        }

        T parent1 = find(element1);
        T parent2 = find(element2);

        //check if the elements are already in the same set
        if (parent1.equals(parent2)) {
            return;
        }

        int rank1 = rankMap.get(parent1);
        int rank2 = rankMap.get(parent2);
        if (rank1 > rank2) {
            parentMap.put(parent2, parent1);
        } else if (rank1 < rank2) {
            parentMap.put(parent1, parent2);
        } else {
            parentMap.put(parent2, parent1);
            rankMap.put(parent1, rank1 + 1);
        }
    }
/**
     * Merges the sets which contain element1 and element2.
     *
     * @param element1 The first element to union.
     * @param element2 The second element to union.
     */
Merges the sets which contain element1 and element2.
@param element1 The first element to union.
@param element2 The second element to union.
Merges the sets which contain element1 and element2 . @param element1 The first element to union . @param element2 The second element to union .
public void union(T element1, T element2)
    {
        if (!parentMap.containsKey(element1)
            || !parentMap.containsKey(element2))
        {
            throw new IllegalArgumentException(
                "elements must be contained in given set");
        }
        T parent1 = find(element1);
        T parent2 = find(element2);
        if (parent1.equals(parent2)) {
            return;
        }
        int rank1 = rankMap.get(parent1);
        int rank2 = rankMap.get(parent2);
        if (rank1 > rank2) {
            parentMap.put(parent2, parent1);
        } else if (rank1 < rank2) {
            parentMap.put(parent1, parent2);
        } else {
            parentMap.put(parent2, parent1);
            rankMap.put(parent1, rank1 + 1);
        }
    }
public void union ( T element1 , T element2 ) { if ( ! parentMap . containsKey ( element1 ) || ! parentMap . containsKey ( element2 ) ) { throw new IllegalArgumentException ( "elements must be contained in given set" ) ; } T parent1 = find ( element1 ) ; T parent2 = find ( element2 ) ; if ( parent1 . equals ( parent2 ) ) { return ; } int rank1 = rankMap . get ( parent1 ) ; int rank2 = rankMap . get ( parent2 ) ; if ( rank1 > rank2 ) { parentMap . put ( parent2 , parent1 ) ; } else if ( rank1 < rank2 ) { parentMap . put ( parent1 , parent2 ) ; } else { parentMap . put ( parent2 , parent1 ) ; rankMap . put ( parent1 , rank1 + 1 ) ; } }
Merges the sets which contain element1 and element2.
Merges the sets which contain element1 and element2 .
//check if the elements are already in the same set