嘿我一直在尝试打印我的哈希表,但即使我使用toArray和toString方法,所有打印的都是内存位置。我真的很困惑,因为我认为阵列和弦都是针对这个问题的。任何帮助,将不胜感激。
我声明我的哈希表如下:
HashTable<Integer,EmployeeInfo> phone = new HashTable<>(300);
同样,当我尝试这些时,我得到的只是内存位置而不是哈希表所包含的实际数据。例如,当我执行phone.toString()时,我得到的是:hashing.HashTable@55f96302。任何帮助将不胜感激,谢谢:)。
package hashing;
import java.util.Arrays;
public class Hash {
public static void main(String[] args) {
// TODO Auto-generated method stub
HashTable<Integer,EmployeeInfo> phone = new HashTable<>(300);
System.out.println(phone.toString());
}
public static class HashTable<K,V>
{
private int numberEntries;
private static final int DEFAULT_CAPACITY = 5;
private HashHolder<K,V>[] hashTable;
private int tableSize;
public HashTable()
{
this(DEFAULT_CAPACITY);
}
public HashHolder<K,V>[] toArray()
{
int size = hashTable.length;
@SuppressWarnings("unchecked")
HashHolder<K,V>[] tempArray = Arrays.copyOf(hashTable,size);//(HashHolder<K,V>[]) new Object[size];
return tempArray;
}
public HashTable(int initCapacity)
{
//Note: I'm not implementing a rigorous check for capacity constraints here. I probably should...
@SuppressWarnings("unchecked")
HashHolder<K,V>[] temp = (HashHolder<K,V>[]) new HashHolder[initCapacity];
hashTable = temp;
numberEntries = 0;
}
}
public static class HashHolder<K,V>
{
private K hashKey;
private V data;
private HashHolder<K,V> next;
private States state;
private enum States {CURRENT,REMOVED};
@Override
public String toString()
{
if(state != States.REMOVED)
return String.format("%s: %s", hashKey.toString(), data.toString());
else
return String.format("REMOVED");
}
public HashHolder(K key, V value)
{
hashKey = key;
data = value;
state = States.CURRENT;
}
}
}
答案 0 :(得分:2)
您的HashTable
类需要自己的toString()
方法,以产生一些合理的输出。否则,您只会从toString
获得默认的Object
行为,该行为会打印出您所看到的无用hashing.HashTable@55f96302
。