Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: The difference between iterators and arraylists

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

like image 477
dukevin Avatar asked Dec 08 '22 04:12

dukevin


1 Answers

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.

Why I would use an iterator instead of using the get() methods of the Arraylist?

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".

like image 181
schematic Avatar answered Apr 02 '23 01:04

schematic