Groovy intersect behavior

Viewed 22

The source code here

https://github.com/groovy/groovy-core/blob/master/src/main/org/codehaus/groovy/runtime/DefaultGroovyMethods.java

public static <T> Collection<T> intersect(Collection<T> left, Collection<T> right) {
    if (left.isEmpty() || right.isEmpty())
        return createSimilarCollection(left, 0);

    if (left.size() < right.size()) {
        Collection<T> swaptemp = left;
        left = right;
        right = swaptemp;
    }

    // TODO optimise if same type?
    // boolean nlgnSort = sameType(new Collection[]{left, right});

    Collection<T> result = createSimilarCollection(left, left.size());
    //creates the collection to look for values.
    Collection<T> pickFrom = new TreeSet<T>(new NumberAwareComparator<T>());
    pickFrom.addAll(left);

    for (final T t : right) {
        if (pickFrom.contains(t))
            result.add(t);
    }
    return result;
}

Says that given

a1.intersect(a2)

if a2 > a1

the order of the result will be of a1?

but I see in https://www.jdoodle.com/execute-groovy-online/

produce the opposite result

def a1 = [1,2,3, 4, 5]
def a2 = [6, 5, 4, 3,2,1]


println a1.intersect(a2)
println a2.intersect(a1)

printing

[5, 4, 3, 2, 1]
[1, 2, 3, 4, 5]

shouldn't the opposite be printed

0 Answers
Related