代码之家  ›  专栏  ›  技术社区  ›  phcaze

ArrayList<文件>包含文件名

  •  0
  • phcaze  · 技术社区  · 12 年前

    我有一个ArrayList(上面代码中的文件)的问题。这个arraylist是由位于sd中的文件组成的。问题是我可能有重复的(相同的图像,但在sd的不同路径中,所以相同的文件名但不同的路径),我想删除它们。所以我使用这个代码:

    ArrayList<File> removedDuplicates = new ArrayList<File>();
    
    for (int i = 0; i < File.size(); i++) {
        if (!removedDuplicates.contains(File.get(i))) {
            removedDuplicates.add(File.get(i));
        }
    }
    

    但我想它不起作用,因为文件列表的contains()会查看文件路径,而不是文件名。这是真的吗?我该如何解决我的问题?我还尝试过:

    ArrayList<File> removedDuplicates = new ArrayList<File>();
    
    for (int i = 0; i < File.size(); i++) {
        if (!removedDuplicates.contains(File.get(i).getName())) {
            removedDuplicates.add(File.get(i));
        }
    }
    

    但它仍然不起作用。谢谢

    3 回复  |  直到 12 年前
        1
  •  2
  •   alex    12 年前

    getName的类型是String,ArrayList中对象的类型是File,所以你永远不会得到同样的东西。

    您想要比较ArrayList中的名称。

    for(File f : files){
        String fName = f.getName();
        boolean found = false;
        for(File f2 : removedDuplicates){
           if(f2.getName().equals(fName)){
               found = true;
               break;
           }
        }
        if(!found){
            removedDuplicates.add(f);
        }
    }
    
        2
  •  1
  •   M-Wajeeh Steve Bergamini    12 年前

    这很简单。 PS:测试代码

    Map<String, File> removedDuplicatesMap = new HashMap<String, File>();
        for (int i = 0; i < files.size(); i++) {
            String filePath = files.get(i).getAbsolutePath();
            String filename = filePath.substring(filePath.lastIndexOf(System
                    .getProperty("file.separator")));
            removedDuplicatesMap.put(filename, files.get(i));
        }
        ArrayList<File> removedDuplicates = new ArrayList<File>(
                removedDuplicatesMap.values());
    
        3
  •  0
  •   bmavus    12 年前

    试试这个:

    ArrayList<File> removedDuplicates = new ArrayList<File>();
    
    File temp;   
    for (int i = 0; i < File.size(); i++) {
       temp=new File(File.get(i).getAbsolutePath());   
       if (!removedDuplicates.contains(temp)) {
             removedDuplicates.add(File.get(i));
       }
    }