0

I have a program that looks like the following attached image, and I'm wondering why the initial array "words" needs to be converted into a list before it can be stored in a HashSet. Can I store it directly in a HashSet? Thank you in advance!

public class Starter {

public int begins(String[] words, String first) {

    HashSet<String> hset = new HashSet(Arrays.asList(words));

    char firstChar = first.charAt(0);

    int total = 0;
    for (String i : hset) {
        if (firstChar == (i.charAt(0))) {
            total += 1;
        }
    }
    return total;
}

}

mgm89
  • 29
  • 2
  • The obvious answer is that there's no HashSet constructor which accepts arrays. That may be because collections are generally preferred. Have a look at https://stackoverflow.com/questions/6100148/collection-interface-vs-arrays – Jan Wilamowski Oct 05 '21 at 05:40

1 Answers1

0
  1. The reason for converting the array into ArrayList is -> HashSet doesn't take an array as a direct argument.

  2. The reason for using HashSet is as it implements Set interface it remove all the duplicate entries and keeps distinct values. For the same reason, you could not check the first letter of a word which occurs multiple times.

So therefore below codes give you output as: 2

public static void main(String[] args) {
        System.out.println(new Solution().begins(new String[] {"hell", "hell", "hock", "tese"}, "h"));
    }
    
    public int begins(String[] words, String first) {

        HashSet<String> hset = new HashSet<>(Arrays.asList(words));

        System.out.println(hset);
        char firstChar = first.charAt(0);

        int total = 0;
        for (String i : hset) {
            if (firstChar == (i.charAt(0))) {
                total += 1;
            }
        }
        return total;
    }
Papai from BEKOAIL
  • 1,469
  • 1
  • 11
  • 17