Reputation: 23
As far as I know, an Iterator is an object which type is defined during its declaration but which also comes with two other methods: hasNext()
and next()
.
So, besides those two methods, if I write Iterator<Integer> iterator
, then iterator is supposed to behave like an Integer object.
However, when I try to use iterator.intValue()
, I get an error.
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
The method intValue() is undefined for the type Class<capture#1-of ? extends Iterator>
Syntax error, insert "}" to complete Block
Here is the full code:
Iterator<Integer> iterator = content.iterator(); //content is a HashSet<Integer> object
System.out.println(iterator.intValue());
while(iterator.hasNext())
{
iterator.next();
System.out.println(iterator);
}
Upvotes: 1
Views: 21728
Reputation: 533500
An Iterator is not an Integer, though it might give you one if you call next()
Instead of calling the Iterator directly is usually better to use a for-each loop which was added to Java 5.0 in 2006.
for(int n : content) //content is a HashSet<Integer> object
System.out.println(n);
From Java 8 you can use the forEach method.
content.forEach(System.out::println);
Upvotes: 0
Reputation: 731
You need to get the Integer from the iterator, then print that Integer:
Integer i = iterator.next();
System.out.println(i);
An Iterator is an iterator for integers, it doesn't behave like an integer. The next method will return an Integer.
Upvotes: 3
Reputation: 311198
No, an Iterator<T>
does not act like a T
- its next()
method, however, returns a T value. I.e.:
while(iterator.hasNext()) {
Integer myInteger = iterator.next();
int myInt = myInteger.intValue();
}
Upvotes: 4