Java中的HashSet冲突

Java中的HashSet冲突

本文介绍了Java中的HashSet冲突的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Java类程序,该程序中我想使用hashSets比较文本文档的目录。本质上,我的计划是为每篇论文创建一个字符串哈希集,然后将其中两个论文的hashSet加到一个hashSet中,并找到相同的6词序列。

I have a program for my Java class where I want to use hashSets to compare a directory of text documents. Essentially, my plan is to create a hashSet of strings for each paper, and then add two of the papers hashSets together into one hashSet and find the number of same 6-word sequences.

我的问题是,我必须手动检查并处理碰撞,还是Java替我做这件事?

My question is, do I have to manually check for, and handle, collisions, or does Java do that for me?

推荐答案

Java哈希映射/集自动处理哈希冲突,这就是为什么同时覆盖 equals hashCode 方法。因为Sets利用它们两者来区分重复项或唯一项。

Java Hash Maps/Sets Automatically handel Hash collisions, this is why it is important to override both the equals and the hashCode methods. As both of them are utilised by Sets to differentiate duplicate or unique entries.

同样重要的是,由于同一哈希引用了多个对象,因此这些哈希冲突会对性能产生影响。

It is also important to note that these hash collisions hava a performance impace since multiple objects are referenced by the same Hash.

public class MyObject {
private String name;

//getter and setters


public int hashCode() {
   int hashCode = //Do some object specifc stuff to gen hashCode
   return int;
}

public boolean equals(Object obj) {
   if(this==obj) return true;
   if(obj instanceOf MyObject) {
       if(this.name.equals((MyObject)obj.getName())) {
           return true;
       }
   return false;
}
}
}

注意:标准Java对象例如因为String已经实现了hashCode和equals,所以您只需要为自己的数据对象执行该操作即可。

Note: Standard Java Objects such as String have already implemented hashCode and equals so you only have to do that for your own kind of Data Objects.

这篇关于Java中的HashSet冲突的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 02:42