2009-06-29 161 views
1

我在Java初學者,不明白if(!s.add(a))意味着在這段代碼摘錄:這個說法是什麼意思?

Set<String> s = new HashSet<String>(); 
for(String a:args) { 
    if(!s.add(a)) System.out.println("Duplicate detected:"+a); 
} 

回答

6

如果集合已經有項目a,那麼add方法將返回false。 !!是一個「不」的操作員,將這個錯誤變爲真實。所以,如果該項目已經在集合中,您將看到println結果。

3

s.add()將返回取決於項目是否被添加到集合中的布爾(真)或不(false)

2

add方法返回一個布爾值,指示添加是否成功。可能是更爲清晰縮進:

Set<String> s = new HashSet<String>(); 
for(String a:args) 
    if(!s.add(a)) 
     System.out.println("Duplicate detected:"+a); 

甚至更​​好用大括號:如果添加失敗顯示

Set<String> s = new HashSet<String>(); 
for(String a:args) { 
    if(!s.add(a)) { 
      System.out.println("Duplicate detected:"+a); 
    } 
} 

消息。

+2

將{}添加到plz中。 – Macarse 2009-06-29 14:19:53

+0

已修復縮進,並添加了{}版本(不要忘記它不是我的代碼...) – 2009-06-29 14:30:14

10

addCollection interface中指定爲返回boolean,指示添加是否成功。來自Javadocs:

如果此集合因呼叫而改變,則返回true。 (如果此collection不允許有重複,並且已經包含了指定的元素,則返回false。)

這段代碼打印出一個消息,如果另外不成功,當是集合重複恰好。

1

s.add(a)只會將a添加到集合中(如果它尚未包含在該集合中)(通過相等)。如果操作導致集合被修改,則add方法返回true

因此如果已經在Set,該add方法將再次添加它,因此修改設定,因此返回false

0

從文檔:

添加到此指定的元素設置 如果它不存在

如果該組已經包含了 元素,呼叫葉集 不變,並返回假。

2

正如其他人回答的那樣,add返回一個布爾值,指示a是否已經添加到集合中。 它相當於

Set<String> s = new HashSet<String>(); 
for(String a:args) { 
    if (s.contains(a)){ 
     System.out.println("Duplicate detected:"+a); 
    } 
    else{ 
     s.add(a); 
    } 
} 

javadoc for the Set interface.

contains 

boolean contains(Object o) 

    Returns true if this set contains the specified element. 
    More formally, returns true if and only if this set contains 
    an element e such that (o==null ? e==null :o.equals(e)). 
0

「!」是'NOT'的符號。

它讀成:

'如果不加參數一到HashSet的S,然後......'

OR

「如果加入一個參數到HashSet的小號返回false,那麼.. '

0

設置數據結構只能包含唯一值。

如果無法添加對象(即,它是重複條目),add(Object)方法將返回false。

如果對象被添加到集合中,該方法將返回true。

0

否設置對象允許重複。 HashSet對象也不允許重複,但get()方法(put()和contains()也)在常量O(k)中運行,所以這是檢查重複項的好方法。

0

主辦供大家參考:

import java.util.Set; 
import java.util.HashSet; 

public class s1 { 
    public static final boolean DUPLICATE = false; 
    public static void main(String[] args) { 
     Set<String> s = new HashSet<String>(); 

     if (!s.add("Hello Bub")) System.out.println("Duplicate detected(1)"); 

     if (s.add("Hello Bub") == DUPLICATE) System.out.println("Duplicate detected(2)"); 
    } 
} 

這似乎更清晰?