今天在學習Collections的源碼時,看到下面的代碼,聯繫以前本身寫的程序,感覺到下面這段代碼確實巧妙:學習
1 public static <T> boolean addAll(Collection<? super T> c, T... elements) { 2 boolean result = false; 3 for (T element : elements) 4 result |= c.add(element); 5 return result; 6 }
下面簡單介紹:spa
「T... elements」 :可變參數列表,元素爲泛型T或T的子類。code
「|=」:這是相似於「+=」這樣的運算式,是A = A + B這種形式的簡寫A+=B;它們是等價的。或「|」運算,二進制運算是同「0」爲「0」,不然爲「1」。邏輯或「|」,同假爲假不然爲真。blog
1 false |= false => 結果爲false; 2 true |= false => 結果爲true; 3 false |= true => 結果爲true; 4 true |= true => 結果爲true;
在第一段代碼中,2號 boolean result = false; 經過後面的運算,只要有一次c.add(element)的運算其中一次返回true,則整個方法的返回值就是true.——我的感受精妙之處在於此(略顯少見多怪)element
邏輯與「&&」 運算源碼
若咱們的需求爲:只要有一次失敗,總體返回失敗。只要有一次爲假,則都爲假。io
1 public class Test { 2 3 public static boolean change(boolean... params){ 4 boolean result = true; 5 for (boolean temp : params) { 6 result = result && temp; 7 } 8 return result; 9 } 10 11 public static void main(String[] args) { 12 System.out.println(Test.change(true, false)); // false 13 System.out.println(Test.change(false, false)); // false 14 System.out.println(Test.change(true, true)); // true 15 } 16 }