Iterator itr=al.iterator();
how does this line eactly work? does it just store the arraylist al in iterator? Can anyone pls give me a detailed explanation.
Thanks in advance.
From the documentation :
An iterator over a collection. Iterator takes the place of Enumeration in the Java Collections Framework. Iterators differ from enumerations in two ways:
Iterators allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics.
Method names have been improved.
http://docs.oracle.com/javase/7/docs/api/java/util/Iterator.html
Basically the iterator maintains a position for iterating over a collection. It can be used to iterate over a collection, with the option of modifying the collection while iterating over it without a ConcurrentModificationException.
Answer:
Returns an iterator over the elements in this list in proper sequence.
Before you can access a collection through an iterator, you must obtain one. Each of the collection classes provides an iterator( ) method that returns an iterator to the start of the collection. By using this iterator object, you can access each element in the collection, one element at a time.
Related
I need an object, that
points to element of linked list
can be iterated to next
can be cloned
all operations should be O(1)
I don't see proofs, that ListIterator complies these requirements. Particularly, I don't see it is Cloneable.
There is no class that fulfill all the criteria for java.util.LinkedList. You need to implement your own linked list for that.
java.util.LinkedList and it's iterators have limitations. Assigning an iterator only creates another reference to the same iterator object, so not "cloneable" assuming that's what you mean by "cloneable". If you create multiple iterators to a list, if any nodes are added or removed from a list, all iterators (except one used for add) will be invalidated. There's no equivalent of C++ std::list::splice(), which can move one or mode nodes within a list or from list to list.
From my understanding, Iterator enables you to go through elements of a Collection. I can understand its use and advantage for an interface that doesn t natively support a get(index) method, but how about for arrayList or Linkedlist?
As LinkedList (or ArrayList) already let me go through each element( with a for loop for example), why someone would still implement an Iterator?
Thanks.
Using the Iterator class when iterating a List is just one among a lot of ways to iterate lists. For an ArrayList it does exactly what you would do with a for loop, iterating with the use of indexes and get(index), just wrapped in the methods of Iterator and ArrayList. For inheritance reasons ArrayList has the functions implemented.
I am confused with a design problem in Java. It realized many abstract containers under the interface Collection and provides the method hasNext() and Next() along with class Iterator. What is the drawback if I put these methods directly under interface Collection and then overrides it in each subclass:
For example, I have already realized Next(); hasNext() method under class ArrayList. So what I wrote is
ArrayList ArrList=new ArrayList()
if(ArrList.hasNext())
new obj=ArrList.next();
}
returning the objects stored in ArrList.
So is it redundant to introduce Iterator class for the interface Collection? And what is the benefit to design ArrList.iterator(); if it's more covenient to set it up in interface?
Can I find any book to solve such oop-design problems(As the computer scientists described it)?
Thanks for your time.
The methods of the Iterator interface (next(), hasNext()) can't simply be added to the interface. An Iterator has a state which determines the next element that would be returned by the iterator.
If the Iterator methods were part of the Collection interface, you would need some additional method to reset this "built-in" iterator (in order to iterate again from the start of the Collection), and you would only have a single iterator for each Collection in any given time. A nested iteration as simple as the following snippet wouldn't be possible, since it requires two iterators :
List<Integer> list = ...
for (int i : list)
for (int j : list)
System.out.println(i+j);
Iterator stores a pointer to some element inside a collection. In case of ArrayList it is an index of the underlying array.
It allows you to say iterate over the collection in two separate threads simultaneously. If the pointer was a part of ArrayList, each of the threads would skip some of the elements.
An iterator is usually made to traversed once. In the Java collection library classes will fail if modifications are made to the underlying collection during a traversal of an iterator.
BTW, this question may be more appropriate for Programmers Stack Exchange which is dedicated to theoretical programming questions.
Let's assume for a moment that ArrayList did have hasNext and next methods, and so your code would compile. (You'd also need another method to tell the list you wanted to start over again.) That would mean that I could only have one iteration of the list active at a time, because the list itself contains the iteration state. That's just poor design; instead, we have the Iterator concept so that the state of the iteration is stored in the iterator, not the list, and we can have multiple iterators.
At the conceptual level: Collection represents a collection of objects. Adding methods for hasNext and next would turn it into a collection of objects along with another piece of state, a 'current object', as well as some concept of how to traverse the collection.
Since these are two separate ideas, it is best to divide them into separate structures that are implemented independently. In the case you speak of, that would be the Collection structure (which handles storage and structure for a collection of objects), and the Iterator structure (which handles position and traversal of some collection of objects).
To remove element from ArrayList, we can use-
Iterator remove() is used while iteration.
For ArrrayList remove() no iteration required.
Syntax is different in those cases. So
Do both use same logic internally?
Is there any more difference than logic?
Which one is better?
Any detailed explanation/link is highly appreciated.
An iterator might throw ConcurrentModificationException if an element is removed from the underlying collection in another way than the iterator's own remove() method.
So if you need to remove elements while iterating over a collection, you're allowed to do that with Iterator.remove() but you can't do that with Collection.remove() without risking to get an exception.
remove is a method that should be implemented (if no, it should throw UnsupportedOperationException) by all objects that are Iterable (implement interface Itarable). The way it works depends always on the object that implements it.
That means an ArrayList can implement it in a totally different way then i.e. LinkedList.
Removing object in Iterator requires You to iterate (find) the object You want to remove.
Using a remove method in ArrayList (there is no delete I can see in Javadoc: http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html) finds the object for You and deletes it. It actually shifts objects in an underlying arrays to fill the "gap" You created by removing the object, so if You want to remove items in a list often, You could use LinkedList Instead.
Additionally while You are iterating through a list, You will cause an exception if You want to modify the collection in some other way than via iterator methods.
The exact answers to Your questions are:
1.No they use diferent logic, and additionally Iterator might even not allow to delete object (UnsupportedOperationException)
2.You cannot remove object by ArrayList remove while You are itereating, and to remove object at position 4 in ArrayList by using Iterator You would have to iterate 4 times "manually".
3.It depends whether You allready know what object do You want to remove, or first You check all the objects and decide whether to delete, during the iteration process. Additionally - If You want to delete objects often, You better use LinkedList, instead of ArrayList.
In java while using the HashMap, they are using the Iterator class. But I can't understand for what purpose they are using Iterator in HashMap?
Entries in a Map are made up of key/value pairs. Iterators can be used to cycle through the set of keys (Map.keySet().iterator()), the set of values (Map.values().iterator(), or both (via the entrySet() method and the Map.Entry<K,V> interface).
For iteration, maybe?
In general, iterators are used to "remember" a point in the collection, so that you can do something to a current element and then move iterator to the next element, and so on...
When you write a code like
for(Value val : collection) { doSomething(val); }
You are implicitly using the collection's iterator.
It is roughly equivalent to writing something like
Iterator<Value> i = collection.iterator();
while(i.hasNext())
{
Value val = i.next();
doSomething(val);
}
Iterators should e used to read the elements from any kind of Collections like ArrayList, HAshMap etc.
They will help us to navigate through the Iterator Objects, if they are not there, how can we retrieve the elements from the collection?
You can iterate through the keys:
myMap.keySet().iterator();
Or you can iterate through the values:
myMap.values().iterator();
These two iterators offered by HashMap allow you to get values (for example) from the map even if you dont know the keys. Or even get a list of the keys.
Iterators provide a way to go over all elements in some order. Not very useful for HashMap, but for TreeMap iterator provides a way go over the elements in increasing order. Similarly for LinkedHashMap one can iterate the way it was inserted.