【发布时间】:2017-03-13 11:26:46
【问题描述】:
我实现了一个 HashMap 并给出了这个输出 (Output1) 你能解释一下哪个元素将存储在哪个桶中。
import java.util.*;
import java.lang.*;
import java.io.*;
class Dog
{
public int i;
public int hashCode()
{
return i+3; // hashcode1
}
Dog(int i)
{
this.i = i;
}
public String toString()
{
return i + "" ;
}
}
class ShellClass
{
public static void main (String[] args) throws java.lang.Exception
{
HashSet s = new HashSet(5,(float)0.8);
for(int i=1; i<=4; i++)
{
s.add((new Dog(i)));
}
System.out.println(s);
}
}
输出是:
Output1 : [1, 2, 3, 4] //with hashcode1
但是,如果哈希码更改为以下:
public int hashCode()
{
return i%3; //hashCode2
}
输出更改为:
Output2: [3, 1, 4, 2] //with hashcode2
【问题讨论】:
标签: hash collections hashset