[Solved] What’s meaning of this method checkDuplicate ? Whats happening inside this code? [closed]


set.add will return false if the element that you wish to add to the Set already exists in the Set (and therefore wasn’t added). Your method returns false if set.add returns false for at least one of the elements of the input List, which means is does what its name implies – checks for duplicates.

public static boolean checkDuplicate(ArrayList<String> list) {

    HashSet<String> set = new HashSet<String>();
    for (int i = 0; i < list.size(); i++) { // iterate over all elements of input list
        boolean isUnique = set.add(list.get(i)); // returns false if list.get(i) 
                                                 // is already in the Set
        if (!isUnique) { // returns false if a non unique element was found
            return isUnique;
        }
    }
    return true; // return true if all the elements in the input List are unique

}

6

solved What’s meaning of this method checkDuplicate ? Whats happening inside this code? [closed]