简体   繁体   English

在Java中散列对象?

[英]Hashing objects in Java?

This is a homework question so I'm not looking for specific implementation but more an understanding of how to implement the following: 这是一个家庭作业问题,所以我不是在寻找具体的实现,而是更多地了解如何实现以下内容:

I have to create a hash table class, I understand how a hash table works but I am confused about how it actually hashes objects. 我必须创建一个哈希表类,我理解哈希表是如何工作的,但我对它实际上是如何哈希对象感到困惑。 In the examples we've seen we generally see integers get stored in a hash table (for simplicity) and they are hashed using an algorithm such as value%10 . 在我们看到的示例中,我们通常会看到整数存储在哈希表中(为简单起见),并使用诸如value%10的算法对它们进行哈希处理。

I'm fine with this but confused about the following. 我很好,但对以下内容感到困惑。 We have been asked to write a class that can take any object and provide methods for insertion etc. I'm not sure how I can call Object%10 considering I can't just find the modulus of an object. 我们被要求编写一个可以接受任何对象并提供插入方法等的类。我不知道如何调用Object%10因为我不能只找到对象的模数。 With this in mind given I'm not to know what sort of object a user could pass to this class (it could be one they have written themselves) how are you expected to write a hash function for all possible objects? 考虑到这一点,我不知道用户可以传递给这个类的对象(它可能是他们自己编写的那个),你期望为所有可能的对象编写一个哈希函数? Am I missing something here? 我在这里错过了什么吗?

I've tried Googling but I'm not exactly sure what to Google so I'm coming up with not much, thanks 我试过谷歌搜索,但我不确定谷歌是什么,所以我想的不多,谢谢

Hashcode doesnt always have to be value%10 , In case of object it is a number derived using state of object ie attributes of object. Hashcode并不总是必须是value%10 ,在对象的情况下,它是使用对象状态(即对象的属性)导出的数字。
If you class like 如果你喜欢上课

public class MyClass {
    int a;
    int b;
}

then Hashcode can be simple as 然后Hashcode可以很简单

public int hashCode() {
    int result = a + b;
    return result;
}

Check the methods of the Object class . 检查Object的方法。 Every object in Java has those methods. Java中的每个对象都有这些方法。 See if one of them can help you. 看看其中一个是否可以帮助你。

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

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