0

Looking through the java source code, I faced with incomprehensible for me construction in the hashCode() method of the class AbstractList. This is implementation of the hashCode method for ArrayList. I don't understand how it iterates with for-each.

 public int hashCode() {
    int hashCode = 1;
    for (E e : this)  //<--???
        hashCode = 31*hashCode + (e==null ? 0 : e.hashCode());
    return hashCode;
}

E is the type of the element. But to which class(type) pointer this belongs?

3 Answers 3

1

But to which class(type) pointer this belongs?

this is the list that hashCode was called on. So the compile-time type is AbstractList<E>.

It's saying "for every element in this list, include that element's hash code in the result".

Sign up to request clarification or add additional context in comments.

1 Comment

This is so easy. Shame on me.
1

The E e refers to the generic type in that ArrayList<E> (see the E?)

Think of it as

ArrayList<String> list 
for(String e : list) {

Only because you're inside the list your list becomes this

Comments

1

List<Person> personList = new ArrayList<Person>();

this - It will refer personList
e - It will refer object of Person class

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.