Java 遍历哈希集时遇到问题

Java 遍历哈希集时遇到问题,java,file,iterator,hashset,Java,File,Iterator,Hashset,我的问题是,当我运行main方法时,没有打印任何内容。 我对HashSets非常陌生,我担心它会因为一些非常愚蠢的事情而无法工作。 dic最初是一个ArrayList,为了提高效率,我正在尝试将其转换为HashSets private Set<String>dic = new HashSet<String>(100000); public void dictionary(){//reads/intializes arraylist dic from a file

我的问题是,当我运行main方法时,没有打印任何内容。 我对
HashSet
s非常陌生,我担心它会因为一些非常愚蠢的事情而无法工作。
dic
最初是一个
ArrayList
,为了提高效率,我正在尝试将其转换为
HashSet
s

private Set<String>dic = new HashSet<String>(100000);
public void dictionary(){//reads/intializes arraylist dic from a file
    File data = new File("dictionaryForJava.txt");
    Scanner scanner=null;
    try {
        scanner = new Scanner(data);
        while (scanner.hasNextLine()) {
            dic.add(scanner.nextLine());
        }
    } catch (FileNotFoundException fnfe) {}
    if(scanner!=null)scanner.close(); // need if if file missing
}
public void print () throws IOException{
     Iterator it = dic.iterator();   
     while(it.hasNext())
         {
              String value =(String)it.next();
              System.out.println(value);  
         }
}
public static void main (String[] args)throws IOException{
    words test = new words();
    test.dictionary();
    test.print();
}
private Setdic=新哈希集(100000);
public void dictionary(){//从文件读取/初始化arraylist dic
文件数据=新文件(“dictionaryForJava.txt”);
扫描器=空;
试一试{
扫描仪=新扫描仪(数据);
while(scanner.hasNextLine()){
dic.add(scanner.nextLine());
}
}catch(FileNotFoundException fnfe){}
if(scanner!=null)scanner.close();//如果文件丢失则需要
}
public void print()引发IOException{
迭代器it=dic.Iterator();
while(it.hasNext())
{
字符串值=(String)it.next();
系统输出打印项次(值);
}
}
公共静态void main(字符串[]args)引发IOException{
单词测试=生词();
test.dictionary();
test.print();
}

很可能找不到文件
dictionaryForJava.txt
。如果不至少打印一些调试信息,就不能接受异常,请尝试以下操作:

catch (FileNotFoundException fnfe) {fnfe.printStackTrace();}

上面将在控制台中显示读取文件时是否出现问题。

它在dictionary()方法中添加了任何内容?您需要在catch块中打印异常。您可能有FileNotFoundException(或)无需读取。请不要隐藏异常(就像您对
FileNotFoundException
所做的那样)。至少,在控制台上记录一个错误。我刚刚运行了它,对我来说它工作正常。当然,只有当命名文件存在并且包含适当的内容时。我同意其他意见。你不应该忽略FileNotFoundException。这段代码也适用于我。读入文件中的行并将其打印出来。问题不在于读入文件,因为当所有内容都是完整的时,它可以完美地工作arrayList@LouisB无论如何,不要吃异常,处理它,并用它做些事情。留下一个空的
catch
块是一种糟糕的做法。将其加载到Eclipse或您最喜欢的IDE中,在dictionary()的开头设置一个断点,然后逐步完成代码