【问题标题】:Why do we need to convert array into a list before storing it in a HashSet?为什么我们需要在将数组存储到 HashSet 之前将其转换为列表?
【发布时间】:2021-11-25 10:01:45
【问题描述】:

我有一个程序,如下图所示,我想知道为什么初始数组“单词”需要转换为列表才能存储在 HashSet 中。我可以将它直接存储在 HashSet 中吗?提前谢谢!

公共类启动器{

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;
}

}

【问题讨论】:

标签: arrays list hashset


【解决方案1】:
  1. 将数组转换为ArrayList的原因是->HashSet不将数组作为直接参数。

  2. 使用HashSet 的原因是因为它实现了Set 接口,它删除了所有重复的条目并保留了不同的值。出于同样的原因,您无法检查多次出现的单词的首字母。

因此下面的代码给你的输出为: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;
    }

【讨论】:

    猜你喜欢
    • 2011-12-22
    • 1970-01-01
    • 1970-01-01
    • 2017-12-29
    • 1970-01-01
    • 1970-01-01
    • 2020-06-15
    • 1970-01-01
    • 2023-03-06
    相关资源
    最近更新 更多