1. 程式人生 > >使用for迴圈為2個List去重,結果詭異

使用for迴圈為2個List去重,結果詭異

為了不在資料庫中重複新增資料,新增之前執行去重。使用2個for迴圈,remove執行次數正常,得到的結果卻不正常,返回的list長度為0,沒有執行remove(Index)的時候也被刪除了,在我的for迴圈中我看不出哪裡有問題。使用Iteater執行remove()則正常。誰要是看出for迴圈有問題麻煩指出一下,謝謝!

 public List<File> deleteSameFile(List<File> list1,List<File> list2){
        //兩個集合先自己去重,再兩個集合一起去重
List<File> tmp1 = new 
ArrayList<>(); //需要新增進去,不能只是引用 tmp1.addAll(deleteSameFile(list1)); List<File> tmp2 = new ArrayList<>(); tmp2.addAll(deleteSameFile(list2)); Log.d(TAG, "deleteSameFile: tmpD長度=" + tmp1.size()); Log.d(TAG, "deleteSameFile: tmpT長度=" + tmp2.size()); if
(tmp1.size()==0){ return tmp2; } Iterator<File> iterator = tmp1.iterator(); Iterator<File> it = tmp2.iterator(); while (it.hasNext()){ String name = it.next().getAbsolutePath(); Log.d(TAG, "deleteSameFile: name="+name); if
(iterator.hasNext()){ String name2 = iterator.next().getAbsolutePath(); Log.d(TAG, "deleteSameFile: name2=" + name2); if(name.equals(name2)){ iterator.remove(); } } } //for迴圈執行之後得到的集合長度為0remove(j)實際只執行了12// for(int i=0; i<tmpT.size(); i++){ // for(int j=0; j<tmpD.size(); j++){ // if(tmpT.get(i).getAbsolutePath().equals(tmpD.get(j).getAbsolutePath())){ // Log.d(TAG, "兩個引數deleteSameFile: tmpD.get(j)=" +tmpD.get(j)); // tmpD.remove(j); // j--; // } // } // // } Log.d(TAG, "兩個引數deleteSameFile: tmpD=" + Arrays.toString(tmp1.toArray())); Log.d(TAG, "兩個引數deleteSameFile: tmpD的集合長度=" + tmp1.size()); List<File> resultList = new ArrayList<>(); if(tmp1.size()>0) resultList.addAll(tmp1); if(tmp2.size()>0) resultList.addAll(tmp2); Log.d(TAG, "deleteSameFile: reusltList="+Arrays.toString(resultList.toArray())); return resultList; }
public List<File> deleteSameFile(List<File> musicList){
    Log.d(TAG, "一個引數deleteSameFile: 集合長度="+musicList.size());
    String name = "用來刪除相同檔案的變數初始化";
    for(int i=0; i<musicList.size(); i++){
        name = musicList.get(i).getAbsolutePath();
        for(int j=i+1; j<musicList.size(); j++){
            if(name.equals(musicList.get(j).getAbsolutePath())){
                musicList.remove(j);
                j--;
                Log.d(TAG, "deleteSameFile: name=" +name);
            }
        }

    }
    Log.d(TAG, "一個引數deleteSameFile: musicList=" + Arrays.deepToString(musicList.toArray()));
    return musicList;
}

用set去重更簡單

/*
方法二:使用set去重 */
public Set<Object> deleteSameFile(Set<Object> set,Set<Object> set2){
    Log.d(TAG, "deleteSameFile: set=" + set.size());
    Log.d(TAG, "deleteSameFile: set2=" + set2.size());
    Set<Object> resutlSet = new LinkedHashSet<>();
    resutlSet.addAll(set);
    resutlSet.addAll(set2);
    Log.d(TAG, "deleteSameFile: resultSet=" + resutlSet.size());
    Iterator<Object> iterator = resutlSet.iterator();
    while(iterator.hasNext()){
        Log.d(TAG, "deleteSameFile: 迭代=" + iterator.next().toString());
    }
    Log.d(TAG, "deleteSameFile: resultSet=" + (Arrays.toString(resutlSet.toArray())));
    return resutlSet;
}