0

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

Lee
  • 142,018
  • 20
  • 234
  • 287
  • Not sure it's relevant to your question, but if you need a `Set` that preserves *insertion* order use a `LinkedHashSet`. Regardless, you should not program to the `HashSet` concrete type but instead to the `Set` interface. – Elliott Frisch Mar 04 '20 at 21:00

2 Answers2

3

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);
}
Óscar López
  • 232,561
  • 37
  • 312
  • 386
0

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);
    }
}
wWw
  • 147
  • 9