Reputation: 11
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
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
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