没有重复读取文件

时间:2011-12-01 18:45:29

标签: java

我有一个文本文件,其中有一个城市列表:

  1. 纽约
  2. 洛杉矶
  3. 芝加哥
  4. 纽约
  5. 多伦多 ECC ...
  6. 我会在java中的列表中加载每一行而不重复。我试图加载它但是当我打印列表时我有重复。

    private Set<Comune> comunilist;
    
    public ReteStradale(){
        comunilist=new HashSet<Comune>(); 
    }
    
    private void loadComuni(String sname){
    
        try{
    
            BufferedReader reader=new BufferedReader(new FileReader(sname));
    
            String id_street=reader.readLine();
    
            while(id_street!=null){
    
                int length=Integer.parseInt(reader.readLine());
                String comune_par=reader.readLine();
                String comune_arr=reader.readLine();
    
                Comune com=new Comune(comune_par);
    
                    comunilist.add(com); 
    
                id_street=reader.readLine();    
            }
    
        }
        catch(FileNotFoundException ffe){
            System.err.println("Error: the file does not exist!");
        }
        catch(IOException ioe){
            ioe.printStackTrace();
        }
    }
    

    这是我的代码。请不要考虑元素的名称而是代码

4 个答案:

答案 0 :(得分:3)

您可以使用Set Data Type,它只存储唯一值。

interface - http://docs.oracle.com/javase/7/docs/api/java/util/Set.html

一个实现 - http://docs.oracle.com/javase/7/docs/api/java/util/HashSet.html

答案 1 :(得分:0)

当你获得每个新城市时,将字符串放入一个集合中。这样可以防止重复。然后,您可以打印Set中的条目。

只要您从文本文件中获取的字符串真的相同,那么您将无法添加重复项。

答案 2 :(得分:0)

我建议您为城市中的城市使用分隔符。

New York, Los Angeles, etc...

然后将城市读入String数组或ArrayList或类似的东西。

完成后,您可以将集合放入不允许重复的Set实现中。

Set<String> mySet = new HashSet<String>(myArrayList);

问候!

答案 3 :(得分:0)

我认为问题出在“Comune”课上。你没有向我们展示代码,我假设你没有在其中实现hashCode()和equals()。

它们的默认实现(来自Object)基于对象的内存地址而不是其内容。因此,即使您使用相同的城市名称创建两个Comune对象,它们也会被Set视为完全不同的对象。

在这种情况下,您应该直接将名称存储为字符串,或者覆盖您的类的两种方法。