2013-02-19 40 views
0

我有一个ArrayList(上面的代码中的文件)的问题。该数组列表由位于sd中的文件组成。问题是我可以有重复(相同的图像,但在不同的路径到SD,所以相同的文件名,但不同的路径),我想删除它们。所以我用这个代码:ArrayList <File>包含文件名

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

但它不工作,我猜是因为含有()用于文件的列表着眼于文件路径,而不是在文件名。这是真的吗?我如何解决我的问题?我也试过:

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

但仍然不起作用。由于

+0

作为建议维护文件名和其它用于路径+文件名2阵列列表中的一个。如果数组列表文件名不包含at中的文件,则添加路径+文件名的数组列表。 – 2013-02-19 07:21:47

+0

相反,进入一个'Map '。会为你节省很多麻烦。 – SudoRahul 2013-02-19 07:23:54

回答

2

类型的getName是String,并在您的ArrayList对象的类型是文件,所以你永远不会得到同样的事情。

您想要比较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); 
    } 
} 
0

试试这个:

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

它很简单。 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());