我如何在java中显示哈希表的内容

时间:2013-11-21 07:08:33

标签: java hashtable

我实现了一个哈希表,我想显示内容,但我不知道该怎么做。

这是我的驱动程序类:

package myHashTable;

import java.util.InputMismatchException;
import java.util.Scanner;

public class MyHashDrivergood{

private static String fileName  = "";
private static int choice   =   0;
private int initialCapacity =   0;
private static String[] testData = null;

public static void main(String[] args){

    Scanner keyboard = new Scanner(System.in);

    MyHashTableTable<String, String> dataTested = new MyHashTableTable<String,String>
                                            ()>;

while( choice != 999 ){

  try {
    System.out.println("Please enter your choice to use the HashTable: (999:
                               End of program) ");
    System.out.println("Read the files, store data in an array,  and display
                               the content: 1 ");
    System.out.println("Read the files and store the data in the HashTable, and 
                               dislay the content of the hashtable: 2");

    choice = keyboard.nextInt();
    keyboard.nextLine();
   } catch (InputMismatchException e) {
    System.out.println("Please enter only numbers!");
    keyboard.nextLine();
    continue;
   }

    switch(choice){

    case 1:
        System.out.print( "Please enter the file name to test:" );
        fileName = keyboard.next();

        testData = new String[MyHashTablegood.getFileSize( fileName )];
        testData = MyHashTablegood.getData( fileName,   
                                MyHashTablegood.getFileSize( fileName ));

        for( int j = 0;j < testData.length; j++ ){
            System.out.println( j + "  " + testData[j] );
        }

        break;

        case 2:
        System.out.print( "Please enter the file name to test:" );
        fileName = keyboard.next();

                //here I read the data from a file

        testData = new String[MyHashTablegood.getFileSize( fileName )];
        testData = MyHashTablegood.getData( fileName,  
                            MyHashTablegood.getFileSize( fileName ));

                    //now I am storing the data in my hash table
        for(int k =0; k < testData.length; k++){
            String data = testData[k];

            dataTested.put(data, data);

        }

        break;

        }
    }

    keyboard.close();

    System.out.println("The program has ended.");

}
}

这是我第一次使用哈希表,而且我不确定自己在做什么。

2 个答案:

答案 0 :(得分:3)

抱歉,当我上班的时候回答得太快了。我以为你在使用HashMap。好吧,如果你想学习如何迭代哈希映射..在这里你去

嗯,一种方法是遍历地图并打印出值

for (Map.Entry<String, String> entry : yourMap.entrySet()) {
    String key = entry.getKey();
    String value = entry.getValue();

    System.out.println ("Key: " + key + " Value: " + value);
}

答案 1 :(得分:1)

你能使用它的toString表示吗?来自Oracle docs of HashTable

String toString()
  

返回表单中此Hashtable对象的字符串表示形式    一组条目,用大括号括起来,用ASCII字符“,”(逗号和空格)分隔。