Java 实现自己的hashset
我在研究java中的hashset,为此我正在编写自己的hashset,每次达到阈值时,它的大小都会翻倍。这里我将阈值保持为原始大小的0.75。然而,我的代码运行在一个无限循环中。我试图调试它,但无法找到我的错误 这是密码Java 实现自己的hashset,java,hash,hashset,Java,Hash,Hashset,我在研究java中的hashset,为此我正在编写自己的hashset,每次达到阈值时,它的大小都会翻倍。这里我将阈值保持为原始大小的0.75。然而,我的代码运行在一个无限循环中。我试图调试它,但无法找到我的错误 这是密码 package drafta; import java.util.Iterator; import java.util.NoSuchElementException; public class HashSet { private Node[] buckets; priv
package drafta;
import java.util.Iterator;
import java.util.NoSuchElementException;
public class HashSet
{
private Node[] buckets;
private int currentSize;
private int current;
public HashSet(int bucketsLength)
{
buckets=new Node[bucketsLength];
currentSize=0;
}
public boolean contains(Object x)
{
return false;
// don't implement for the draft
}
public boolean add(Object x)
{
int key=gethashcode(x);
Node node = buckets[key];
while(node!=null){
if(node.data.equals(x)){
return false;
}
}
if(buckets[current]==null){
node = new Node(x);
current=key;
buckets[key]=node;
currentSize++;
}else{
node = new Node(x);
node.next=buckets[current];
current=key;
buckets[key]=node;
currentSize++;
}
System.out.println("add successful "+ x);
System.out.println(" size "+currentSize+" rehash "+buckets.length*0.75);
if(currentSize>(buckets.length*0.75)){
rehash();
}
return true;
}
private void rehash() {
Node temp=buckets[current];
Object s[]=new Object[buckets.length];
buckets=new Node[2*buckets.length];
currentSize=0;
int i=0;
while(temp!=null){
s[i]=temp.data;
temp=temp.next;
i++;
}
while(i>0){
add(s[--i]);
}
}
public boolean remove(Object x)
{
return false;
// don't implement for draft
}
public int gethashcode(Object x){
int hc = x.hashCode();
if(hc<0)
hc=-hc;
return (hc%buckets.length);
}
public Iterator<Object> iterator()
{
Iterator <Object> i=new HashSetIterator();
return i;
//
}
public int size()
{
return currentSize;
//
}
private void resize(int newLength)
{
}
public int getlength()
{
return buckets.length;
//
}
class Node
{
public Object data;
public Node next;
public Node(Object x) {
data=x;
}
public String toString(){
return data.toString();
}
}
class HashSetIterator implements Iterator<Object>
{
private int bucket=0;
private Node currentnode;
public HashSetIterator()
{
currentnode=buckets[current];
}
public boolean hasNext()
{
if(currentnode.next!=null)
return true;
else
return false;
//
}
public Object next()
{
return currentnode.next;
//
}
@Override
public void remove() {
currentnode.next=currentnode.next.next;
}
}
}
有人能指出我的错误吗..当代码第二次调用rehash时,代码将进入infinite循环..第一次正确通过..您不能在
add
方法中更改while循环中的任何条件-因此没有理由中断
while(node!=null){
if(node.data.equals(x)){
return false;
}
}
您将继续循环,直到节点为null(从未设置)或节点数据始终等于x,但数据值也从未设置。一直以来,我都认为我的重新设置是个问题,,,非常感谢…额外的眼睛总是有帮助的。
while(node!=null){
if(node.data.equals(x)){
return false;
}
}