向 Vector 解释哈希码

发布于 2024-10-31 02:43:56 字数 320 浏览 5 评论 0原文

我可以了解哈希码如何根据添加到向量的元素获取值吗?

  Vector v = new Vector();

  //Add elements to Vector
  v.add("1");
  System.out.println(v.hashCode());
  v.add("2");
  System.out.println(v.hashCode());
  v.add("=");
  System.out.println(v.hashCode());

哈希码值为

 80
 2530
 78491

Can I get an idea of how the hashcode takes the valueas per the element added to vector?

  Vector v = new Vector();

  //Add elements to Vector
  v.add("1");
  System.out.println(v.hashCode());
  v.add("2");
  System.out.println(v.hashCode());
  v.add("=");
  System.out.println(v.hashCode());

The hashcode values are

 80
 2530
 78491

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

镜花水月 2024-11-07 02:43:56

它对于 List 接口的每个(真正的)实现都是相同的(如果它支持添加元素)。 .hashCode 方法的行为在 List.hashCode() 如下:

返回此列表的哈希码值。列表的哈希码定义为以下计算的结果:

 int hashCode = 1;
 迭代器 i = list.iterator();
 while (i.hasNext()) {
     E obj = i.next();
     hashCode = 31*hashCode + (obj==null ? 0 : obj.hashCode());
 }

这确保了 list1.equals(list2) 意味着任意两个列表的 list1.hashCode()==list2.hashCode()
list1list2,按照Object.hashCode()通用合约的要求。

正如glowcoder 所示,AbstractList 只包含此实现,因此并非List 接口的每个实现者都必须再次执行此操作。

例如,您还可以编写 Arrays.asList("1", "2").hashCode() 并得到相同的 2530(只要您不更改 hashCode () String 的实现)。

It works the same for every (true) implementation of the List interface (if it supports adding elements). The behavior of the .hashCode method is defined in List.hashCode() as follows:

Returns the hash code value for this list. The hash code of a list is defined to be the result of the following calculation:

 int hashCode = 1;
 Iterator<E> i = list.iterator();
 while (i.hasNext()) {
     E obj = i.next();
     hashCode = 31*hashCode + (obj==null ? 0 : obj.hashCode());
 }

This ensures that list1.equals(list2) implies that list1.hashCode()==list2.hashCode() for any two lists,
list1 and list2, as required by the general contract of Object.hashCode().

As glowcoder showed, AbstractList contains just this implementation, and thus not every implementor of the List interface has to do this again.

For example, you also could write Arrays.asList("1", "2").hashCode() and would get the same 2530 (as long as you don't change the hashCode() implementation of String).

意中人 2024-11-07 02:43:56

因为 Vector 扩展了 AbstractList,所以它使用它作为它的 hashCode。这就是它的作用。

public int hashCode() {
int hashCode = 1;
Iterator<E> i = iterator();
while (i.hasNext()) {
    E obj = i.next();
    hashCode = 31*hashCode + (obj==null ? 0 : obj.hashCode());
}
return hashCode;
}

Because Vector extends AbstractList, it uses it for it's hashCode. Here's what it does.

public int hashCode() {
int hashCode = 1;
Iterator<E> i = iterator();
while (i.hasNext()) {
    E obj = i.next();
    hashCode = 31*hashCode + (obj==null ? 0 : obj.hashCode());
}
return hashCode;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文