2015-08-20 66 views
-2
public class MyClass extends Activity { 
    public static final String DEFAULT_ID = "def"; 
    public static final LinkedHashSet<String> DEF_IDS = new LinkedHashSet<>(Arrays.asList(DEFAULT_ID)); 

    private boolean isDefault(String currentId) { 
     Log.v(TAG,"isdefault("+currentId+") = " + DEF_IDS.contains(currentId)); 
     return DEF_IDS.contains(currentId); 
    } 
} 

在日誌返回true?如果DEF_IDS不包含「profile0」,它爲什麼說它包含?LinkedHashSet.contains()時,它應該返回false

+1

是它'profile0'(變量)或' 「PROFILE0」'? – dotvav

+0

這意味着在調用'isDefault()'之前有人把它放在這裏。原因可能是'DEF_IDS'是靜態的並且在類之間共享。 –

+0

我剛剛測試了你的代碼,[它按預期工作](https://ideone.com/zszk17)。其他的一定是錯的。 – Tunaki

回答

0

錯誤不在您發佈的代碼中。以下產生預期的結果。

public static final String DEFAULT_ID = "def"; 
public static final LinkedHashSet<String> DEF_IDS = new LinkedHashSet<>(Arrays.asList(DEFAULT_ID)); 

private static boolean isDefault(String currentId) { 
    return DEF_IDS.contains(currentId); 
} 

private void test(String def) { 
    System.out.println("isDefault(" + def + ") = " + isDefault(def)); 
} 

public void test() { 
    test("def"); 
    test(DEFAULT_ID); 
    test("NOT"); 
} 

通過打印

isDefault(def) = true 
isDefault(def) = true 
isDefault(NOT) = false 
0

執行的下面的代碼,它給了我正確的結果。
問題似乎是你使用靜態LinkedHashSet,它會保留以前的值,直到你不會明確地清除它,即只初始化一次。

添加更多詳細信息或關閉您的問題,因爲它一點也不清楚,也沒有提供關於您如何使用此代碼的完整上下文。

public static final String DEFAULT_ID = "def"; 
      public static final LinkedHashSet<String> DEF_IDS = new LinkedHashSet<>(Arrays.asList(DEFAULT_ID)); 


     public static void main(String[] args){ 
      isDefault("profile0"); 
     } 
      private static boolean isDefault(String currentId) { 
       System.out.println("isdefault("+currentId+") = " + DEF_IDS.contains(currentId)); 
       return DEF_IDS.contains(currentId); 
      } 

輸出: - ISDEFAULT(PROFILE0)=假

相關問題