简体   繁体   English

关于java中AbstractList的hashCode function的问题

[英]A question about the hashCode function of AbstractList in java

At line 540, why could we use this pointer of AbstractList in foreach?在第 540 行,为什么我们可以在 foreach 中使用 AbstractList 的这个指针?

538. public int hashCode() {
539.     int hashCode = 1;
540.     for (E e : this)
541.         hashCode = 31*hashCode + (e==null ? 0 : e.hashCode());
542.     return hashCode;
543. }

Screenshot截屏

It iterates over the list items and create a hash code depended for that.它遍历列表项并为此创建一个 hash 代码。 For every item you add or remove from list changes hashcode.对于您从列表中添加或删除的每个项目,都会更改哈希码。 This is the default implementation to create uniqueness for a list.这是为列表创建唯一性的默认实现。

The question can be divided in two parts:问题可以分为两部分:


"why could we use this pointer of AbstractList" “为什么我们可以使用 AbstractList 的指针”

this always returns the actual instance; this总是返回实际的实例; it is also valid in an abstract class, being similar, in that case, to a parameter defined as AbstractList this initialized with the actual instance.它在abstract class 中也有效,在这种情况下,类似于定义为AbstractList this的参数,该参数使用实际实例进行初始化。 Like in:像:

public int hashCode(AbstractList this) {
    ...
}

See JLS 15.8.3.JLS 15.8.3。 this for more details.了解更多详情。


"why could we use... AbstractList in foreach" “为什么我们可以在 foreach 中使用... AbstractList”

the AbstractList can be used in the enhanced for loop because it implements the Iterable interface. AbstractList可以在增强for循环中使用,因为它实现了Iterable接口。 See documentation JLS 14.14.2.请参阅文档JLS 14.14.2。 The enhanced for statement : 增强的 for 语句

The type of the Expression must be a subtype of the raw type Iterable or an array type Expression 的类型必须是原始类型 Iterable 的子类型或数组类型

and of Iterable :Iterable

Implementing this interface allows an object to be the target of the enhanced for statement (sometimes called the "for-each loop" statement).实现此接口允许 object 成为增强 for 语句(有时称为“for-each 循环”语句)的目标。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM