Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Hey everyone! I have this method that used to be an ArrayList and I\'m trying to

ID: 3528089 • Letter: H

Question

Hey everyone! I have this method that used to be an ArrayList and I'm trying to change it line-by-line in order to turn it into a HashSet and have it do the same thing (in order to lower compile/run time). This is what I have so far, but since Sets don't have get methods, I need to somehow replace it with something else. I'm not too familiar with iterators but I'm assuming that's the way to go?

public static Set<String> getOverlap(HashSet<String> list1,

HashSet<String> list2) {

Set<String> result = new HashSet<String>();

int index1 = 0;

int index2 = 0;

while (index1 < list1.size() && index2 < list2.size()) {

int comparison = list1.get(index1).compareTo(list2.get(index2));

if (comparison == 0) {

result.add(list1.get(index1));

index1++;

index2++;

} else if (comparison < 0) {

index1++;

} else { // comparison > 0

index2++;

}

}

return result;

}

Explanation / Answer

This solves your problem

public static Set<String> getOverlap(HashSet<String> list1,    HashSet<String> list2) {
        Set<String> result = new HashSet<String>();
        int index1 = 0;
        int index2 = 0;

        String[] list1Strings = (String[])list1.toArray();
        String[] list2Strings = (String[])list2.toArray();
       
        while (index1 < list1.size() && index2 < list2.size()) {

            int comparison = list1Strings[index1].compareTo(list2Strings[index2]);

            if (comparison == 0) {

                result.add(list1Strings[index1]);

                index1++;

                index2++;

            } else if (comparison < 0) {

                index1++;

            } else { // comparison > 0

                index2++;

            }

        }

        return result;

    }