Reputation: 157
I'm trying to iterate over the Integer objects of a HashSet
and I want to count the number of times an element occurs. this is my method so far
public int freq(int element) {
int numElements = 0;
for (int atPos : mySet){
if (mySet.atPos == element){ //says atPos cannot be resolved to a field
numElements++;
}
}
return numElements;
}
would it be better to use an iterator to iterate over the elements? How do I fix my
mySet.atPos
line?
This is where I initialize my HashSet
private HashSet <Integer> mySet = new HashSet<Integer>();
Upvotes: 0
Views: 671
Reputation: 44250
Your issue is a simple misunderstanding of how you can use variables. int atPos
and mySet.atPos
do not refer to the same thing. The former refers to a local variable, the latter is looking for a public member of field of an instance of a set called the same thing.
You are trying to access this field:
public class HashSet
{
public int atPos; //<<<
}
but, when we think of it this way, obviously that field does not exist in HashSet
!
All you need to do is get rid of mySet.
and your code will work.
if (atPos == element){
numElements++;
}
Would it be better to use an iterator to iterate over the elements?
No, there's no benefit to using an iterator in this situation. A for each is more readable.
As others have noted, because sets will never contain duplicates, your numElements
will actually only ever be one or zero. As such, you could actually write your function very compactly as:
public int freq(int element) {
if (myset.contains(element)) {
return 1;
}
else {
return 0;
}
}
Or even better using the ternary operator:
public int freq(int element) {
return myset.contains(element) ? 1 : 0;
}
Upvotes: 1
Reputation: 2344
A Set cannot contain duplicate elements. Therefore you will always get a count of 0 or 1 for your element
.
For any collection, you can get the frequency of the elements with:
public int freq(int element) {
return Collections.frequency(mySet, element);
}
Not sure you'd want to make a method out of it ...
Upvotes: 2