简体   繁体   English

使用 for 循环遍历 HashSet

[英]Iterating through a HashSet using a for loop

I have a HashSet that I would like to iterate through a for loop and display its contents but I don't know how to make it work.我有一个 HashSet,我想遍历 for 循环并显示其内容,但我不知道如何使其工作。 I can't seem to find a way to access an element of a certain index(i) of a HashSet.我似乎无法找到一种方法来访问 HashSet 的某个索引(i)的元素。 Is there a way to do this?有没有办法做到这一点?

I have the following (non-compiling) code as my basis of what I want to achieve:我有以下(非编译)代码作为我想要实现的基础:

    public void postNumbers(HashSet<String> uniqueNumbers)
    {
        for (int i = 0; i < uniqueNumbers.size(); i++)
        {
            System.out.println(uniqueNumbers(i));
        }
    }

I'd like to replace the System.out.println portion of the code (specifically uniqueNumbers(i)) but I don't know how to approach it我想替换代码的 System.out.println 部分(特别是 uniqueNumbers(i)),但我不知道如何处理它

Sets don't have indexes, so your approach for traversing its elements won't work.集合没有索引,因此您遍历其元素的方法将不起作用。 Better use an enhanced for loop, like this:更好地使用增强的 for 循环,如下所示:

for (String number : uniqueNumbers) {
    System.out.println(number);
}

HashSet does not order its elements, thus referring to specific index does not work. HashSet不对其元素进行排序,因此引用特定索引不起作用。 To loop through elements in a HashSet , use for loop as following:要循环遍历HashSet元素,请使用 for 循环,如下所示:

public void postNumbers(HashSet<String> uniqueNumbers)
{
    for (String n : uniqueNumbers)
    {
        System.out.println(n);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM