How would you explain to someone who has just started programming in Java, what the difference between ArrayLists and Iterators are?
Why I would use an iterator instead of using the get() methods of the Arraylist
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
An ArrayList is an actual data structure, an implementation of the List interface. An Iterator is just an interface that allows you to navigate through any data structure (as long as an Iterator is available for that data structure).
In other words, an ArrayList is an actual list of object references (or primitives) stored physically in an array. ArrayList is an “implementation” of the List interface, meaning it provides implementations of all the methods that are applicable to a List, such as add(object), remove(object), get(index), etc.
Iterator is a more generic way to navigate through any data structure, be it a Set, a List, whatever. One important point is that it lets you navigate through every element in the data structure once, and then you’re done. From the documentation you can see that Iterator prescribes two methods, next() and hasNext(). next returns the next element in the underlying data structure, and hasNext lets you know if there even is a next element in the underlying data structure. Several data structures, ArrayList included, can provide you with an Iterator.
Well, like many interfaces, Iterator allows you to do the same kind of thing no matter what the underlying implementation. If I want to “iterate” through some data structure, I can either
a) write code that is specifically geared toward the data structure (such as an ArrayList) that I will have to change later if I change the data structure to something else (such as a HashSet) or
b) obtain an Iterator from the data structure, and use the same hasNext/next technique that will work even if I change the data structure to something else.
FYI, if you aren’t too familiar with the words “interface” and “implementation” you should probably do a Google search on “Java interface”.