Reputation: 33
I am new to Java. I have a question about the time complexity of java iterator().
Set<Integer> set = new HashSet<>();
Iterator<Integer> iter = set.iterator(); ==> (2)
I wanna know what is the time complexity of step 2? It is const time O(1) or it depends on the size of set?
Thanks
Upvotes: 3
Views: 13489
Reputation: 1279
Calling iterator()
is constant time. It is a method call that returns an Iterator
instance on the collection you are calling on. Actually iterating through the collection using the iterator using while (hasNext())
will be O(n)
Upvotes: 3
Reputation: 31841
When you call the iterator()
method, you're not looping anywhere. This method just returns an iterator over the elements and that time is constant, and thus you don't calculate time-complexity for this.
You calculate the time-complexity wherever you're accessing the elements from a group of elements. For example, when you access the elements like this:
while(iterator.hasNext()) {
Object element = iterator.next();
}
This is where you can calculate the time complexity, and in this case it will be O(n)
.
Upvotes: 1