HomeWork3
- 这个作业主要是让我们学习如何hash化。我这里就将我修改的部分粘贴过来,原文有的我就不放这里了。
- 对hash化而言,最主要是如何将对象转化成int类型,方便储存和寻址。
- 这里是
-
通过和类似于进制的思路
因为一共有255/5 = 51 51+1=52
因此将其当成3位52进制 进行计算
@Override
public class SimpleOomage implements Oomage {
public boolean equals(Object o) {
// TODO: Write this method.
if (this == o) return true;
if (o == null) return false;
if (this.getClass() != o.getClass()) return false;
SimpleOomage so = (SimpleOomage) o;
return red == so.red && green == so.green && blue == so.blue;
}
/* Uncomment this method after you've written
equals and failed the testHashCodeAndEqualsConsistency
test.*/
//使用自定义hashcode 而不使用原有的hashcode
@Override
public int hashCode() {
if (!USE_PERFECT_HASH) {
return red + green + blue;
} else {
// TODO: Write a perfect hash function for Simple Oomages.
// 通过和类似于进制的思路
// 因为一共有255/5 = 51 51+1=52
// 因此将其当成3位52进制 进行计算
return red / 5 * 52 * 52 + green / 5 * 52 + blue / 5;
}
}
}
- 这里对hashcode进行了评估,N 表示 oomages中有多少的item,M表示一个bucket有多少个格子,在进行性能评估的时候,不要使用M,而是要使用N。
public class OomageTestUtility {
public static boolean haveNiceHashCodeSpread(List<Oomage> oomages, int M) {
/* TODO:
* Write a utility function that returns true if the given oomages
* have hashCodes that would distribute them fairly evenly across
* M buckets. To do this, convert each oomage's hashcode in the
* same way as in the visualizer, i.e. (& 0x7FFFFFFF) % M.
* and ensure that no bucket has fewer than N / 50
* Oomages and no bucket has more than N / 2.5 Oomages.
*/
int[] bucket = new int[M];
Arrays.fill(bucket, 0);
for (Oomage o : oomages) {
int bucketNum = (o.hashCode() & 0x7FFFFFFF) % M;
bucket[bucketNum]++;
}
// 材料中的N表示的是oomages的数目
// M表示Hash表的格子数