+ 1

why is this method written two times in ArrayList class?

in ArrayList<E> generic class there are two method of the same name. or in another word there's a method which is written two time but with different return values. and that is: Iterator<E> iterator() and it has not been even overloaded! they are written this way: public Iterator<E> iterator() { return listIterator(); } and: public Iterator<E> iterator() { return new Itr(); } I really couldn't understand this. maybe I have missed sth in learning collections? how the caller method will know which one to call? cause this method is not even overloaded

1st Aug 2019, 5:05 PM
salar vahidi
salar vahidi - avatar
2 Answers
+ 3
Interesting question... Basically you have two classes, ArrayList and its inner class SubList, one method is defined inside ArrayList and the other one is defined inside inner class SubList. Therefore, if you want to call method from SubList, then you will have to use different dot notation than when you call method from outside of SubList, and since SubList is private you would be able to call it only inside ArrayList... Anyway here's the answer I found on stackoverflow: https://stackoverflow.com/questions/44351441/overriding-same-method-twice-from-same-class/44351452#44351452
1st Aug 2019, 5:47 PM
voja
voja - avatar
+ 1
@voja oh you are right I didn't see that innerclass thank you so much it was really frustrating to not know what's going on
1st Aug 2019, 6:35 PM
salar vahidi
salar vahidi - avatar