【问题标题】:ArrayList<File> contains filenameArrayList<File> 包含文件名
【发布时间】:2013-02-03 19:13:58
【问题描述】:

我对 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));
    }
}

但它仍然不起作用。谢谢

【问题讨论】:

  • 建议维护 2 个数组列表,一个用于文件名,另一个用于路径+文件名。如果数组列表文件名不包含 at 中的文件,则添加路径+文件名的数组列表。
  • 相反,请加入Map&lt;String, File&gt;。将为您省去很多麻烦。

标签: android arraylist contains


【解决方案1】:

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】:

    它非常简单。 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】:

      试试这个:

      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));
         }
      }
      

      【讨论】:

        猜你喜欢
        • 2017-03-19
        • 2017-07-30
        • 2013-03-23
        • 2016-04-09
        • 1970-01-01
        • 1970-01-01
        • 2021-08-03
        • 1970-01-01
        • 2018-12-06
        相关资源
        最近更新 更多