Kayle Smith
Kayle Smith

Reputation: 11

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. I can't seem to find a way to access an element of a certain index(i) of a HashSet. 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

Upvotes: 0

Views: 2631

Answers (2)

wWw
wWw

Reputation: 192

HashSet does not order its elements, thus referring to specific index does not work. To loop through elements in a HashSet, use for loop as following:

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

Upvotes: 0

&#211;scar L&#243;pez
&#211;scar L&#243;pez

Reputation: 236150

Sets don't have indexes, so your approach for traversing its elements won't work. Better use an enhanced for loop, like this:

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

Upvotes: 3

Related Questions