java新手抖機靈(java新手技巧)
阿新 • • 發佈:2018-11-20
1.交換兩個整數的值
好處是不用定義臨時變數,顯得程式碼簡潔,提高執行效率
其實也可以用+-*/進行這種運算
比如可以這樣:
a = a + b;
b = a - b;
a = a - b;
int a = 1, b = 2;
a = a ^ b;
b = a ^ b;
a = a ^ b;
System.out.println(a);
System.out.println(b);
2.快速查詢整形陣列中的偶數
其實這個和第四項有些重複部分,但是總覺得合在一起不合適,所以好吧,還是單獨寫了出來,
第二種方法請參照第四條,更易於理解
int[] a = {-1, 1, 2, 3, 4, 5, 6, 7, 8, 9};
int count = 0;
for (int i : a) {
count += i&1;
}
System.out.println(count);
3.java自動關閉流
這個可以說是我學python回來之後遇到的最好的語法糖了,對於習慣性忘記關閉流的我來說,真的是很舒服
try (PrintWriter pw = new PrintWriter("d:/temp.txt"); FileReader fr = new FileReader("d:temp.txt"); BufferedReader br = new BufferedReader(fr)) { pw.write("你好我是小言"); pw.flush(); System.out.println(br.readLine()); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }
4.快速判斷一個數是否為偶數
前面說過了,其實這個按位符號用途還蠻多的,新手瞭解的話很費勁,在學校老師也不會怎麼教實際應用,直到我看到了這個,才對按位運算起了興趣
//方法1,速度較快
for (int i = -10; i < 10; i++) {
System.out.println((i&1)==0);
}
//方法2,便於理解
for (int i = -10; i < 10; i++) {
System.out.println(i*i%2==0);
}