Feuermagier / autograder

Automatic grading of student's Java code
MIT License
13 stars 7 forks source link

`api.CheckIterableDuplicates` does not detect code where `contains` is used in addition to `add` #502

Open Luro02 opened 2 months ago

Luro02 commented 2 months ago

Summary

See the example below.

Lint Name

COMMON_REIMPLEMENTATION_ITERABLE_DUPLICATES

Reproducer

    private static boolean hasDuplicates(List<String> list) {
        Set<String> uniqueElements = new HashSet<>();

        for (String element : list) {
            if (uniqueElements.contains(element)) {
                return true; // Found a duplicate
            } else {
                uniqueElements.add(element);
            }
        }

        return false; // No duplicates found
    }
    private static boolean hasDuplicates(List<String> list) {
        Set<String> uniqueElements = new HashSet<>();

        for (String element : list) {
            if (uniqueElements.contains(element)) {
                return true; // Found a duplicate
            }

            uniqueElements.add(element);
        }

        return false; // No duplicates found
    }

and this one should not trigger:

    private static boolean hasDuplicates(List<String> list) {
        Set<String> uniqueElements = new HashSet<>();

        for (String element : list) {
            uniqueElements.add(element);

            if (uniqueElements.contains(element)) {
                return true; // Found a duplicate
            }
        }

        return false; // No duplicates found
    }

(the contains has to be before the add call)