2015-07-11 75 views
-5
public static boolean checkDuplicate(ArrayList<String> list) { 

     HashSet<String> set = new HashSet<String>(); 
     for (int i = 0; i < list.size(); i++) { 
      boolean isUnique = set.add(list.get(i)); 
      if (!isUnique) { 
       return isUnique; 
      } 
     } 
     return true; 

    } 
+0

它檢查列表中是否有任何重複的元素。如果有任何重複,則返回'false'。如果沒有重複,則返回'true'。 'set.add(x)'如果'x'不在集合中,則返回'true'。 – khelwood

+0

你能說說每一行代碼會發生什麼嗎? – Senthu

回答

0

set.add將返回false如果您希望添加到Set中的元素已經存在於Set中(因此未添加)。如果set.add對於輸入列表中的至少一個元素返回false,這意味着它的名字意味着 - 檢查重複項,則返回false

public static boolean checkDuplicate(ArrayList<String> list) { 

    HashSet<String> set = new HashSet<String>(); 
    for (int i = 0; i < list.size(); i++) { // iterate over all elements of input list 
     boolean isUnique = set.add(list.get(i)); // returns false if list.get(i) 
               // is already in the Set 
     if (!isUnique) { // returns false if a non unique element was found 
      return isUnique; 
     } 
    } 
    return true; // return true if all the elements in the input List are unique 

} 
+0

謝謝。很好理解。我是這個網站的新手。我有更多問題我該如何問 – Senthu

+0

@Senthu不客氣!歡迎來到Stack Overflow。如果您有其他問題,只需發表另一個問題。 – Eran

+0

無法發佈問題。它說我可以在90分鐘後發帖 – Senthu

0

在'設置'接口添加方法有布爾返回類型。 Set僅包含唯一值。如果您嘗試插入重複值,則返回false。

+0

你可以說說每一行代碼會發生什麼? – Senthu

+0

哪一行代碼讓你困惑? – gifpif

+0

爲什麼使用HashSet set = new HashSet ();這個代碼?還有boolean isUnique = set.add(list.get(i)); if(!isUnique){ return isUnique; } – Senthu