讓代碼性能更高
1.需要 Map 的主鍵和取值時,應該迭代 entrySet()
當循環中只需要 Map 的主鍵時,迭代 keySet() 是正確的。但是,當需要主鍵和取值時,迭代 entrySet() 纔是更高效的做法,比先迭代 keySet() 後再去 get 取值性能更佳。
反例
Map<String,String> map = ...;
for(String key: map.keySet()) {
String value = map.get(key);
...
}
正例
Map<String,String> map = ...;
for (Map.Entry<String, String> entry : map.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
...
}
2.應該使用Collection.isEmpty()檢測空
使用 Collection.size() 來檢測空邏輯上沒有問題,但是使用 Collection.isEmpty()使得代碼更易讀,並且可以獲得更好的性能。任何 Collection.isEmpty() 實現的時間複雜度都是 O(1) ,但是某些 Collection.size() 實現的時間複雜度可能是 O(n) 。
反例
if (collection.size() == 0) {
...
}
正例
if (collection.isEmpty()) {
...
}
3.集合初始化儘量指定大小
java 的集合類用起來十分方便,但是看源碼可知,集合也是有大小限制的。每次擴容的時間複雜度很有可能是 O(n) ,所以儘量指定可預知的集合大小,能減少集合的擴容次數。
反例
int[] arr = new int[]{1, 2, 3};
List<Integer> list = new ArrayList<>();
for (int i : arr) {
list.add(i);
}
正例
int[] arr = new int[]{1, 2, 3};
List<Integer> list = new ArrayList<>(arr.length);
for (int i : arr) {
list.add(i);
}
4.字符串拼接使用 StringBuilder
一般的字符串拼接在編譯期 java 會進行優化,但是在循環中字符串拼接, java 編譯期無法做到優化,所以需要使用 StringBuilder 進行替換。
反例
String s = "";
for (int i = 0; i < 10; i++) {
s += i;
}
正例
String a = "a";
String b = "b";
String c = "c";
String s = a + b + c; // 沒問題,java編譯器會進行優化
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 10; i++) {
sb.append(i); // 循環中,java編譯器無法進行優化,所以要手動使用StringBuilder
}
5.List 的隨機訪問
數組和鏈表的區別:數組的隨機訪問效率更高。當調用方法獲取到 List 後,如果想隨機訪問其中的數據,並不知道該數組內部實現是鏈表還是數組,怎麼辦呢?可以判斷它是否實現 RandomAccess 接口。
正例
// 調用服務獲取到list
List<Integer> list = otherService.getList();
if (list instanceof RandomAccess) {
// 內部數組實現,可以隨機訪問
System.out.println(list.get(list.size() - 1));
} else {
// 內部可能是鏈表實現,隨機訪問效率低
}
6.頻繁調用 Collection.contains 方法請使用 Set
在 java 集合類庫中,List 的 contains 方法普遍時間複雜度是 O(n) ,如果在代碼中需要頻繁調用 contains 方法查找數據,可以先將 list 轉換成 HashSet 實現,將 O(n) 的時間複雜度降爲 O(1) 。
反例
ArrayList<Integer> list = otherService.getList();
for (int i = 0; i <= Integer.MAX_VALUE; i++) {
// 時間複雜度O(n)
list.contains(i);
}
正例
ArrayList<Integer> list = otherService.getList();
Set<Integer> set = new HashSet(list);
for (int i = 0; i <= Integer.MAX_VALUE; i++) {
// 時間複雜度O(1)
set.contains(i);
}
讓代碼更優雅
1.長整型常量後添加大寫 L
反例
long value = 1l;
long max = Math.max(1L, 5);
正例
long value = 1L;
long max = Math.max(1L, 5L);
2.不要使用魔法值
當你編寫一段代碼時,使用魔法值可能看起來很明確,但在調試時它們卻不顯得那麼明確了。這就是爲什麼需要把魔法值定義爲可讀取常量的原因。但是,-1、0 和 1不被視爲魔法值
反例
for (int i = 0; i < 100; i++){
...
}
if (a == 100) {
...
}
正例
private static final int MAX_COUNT = 100;
for (int i = 0; i < MAX_COUNT; i++){
...
}
if (count == MAX_COUNT) {
...
}
3.不要使用集合實現來賦值靜態成員變量
對於集合類型的靜態成員變量,不要使用集合實現來賦值,應該使用靜態代碼塊賦值。
反例
private static Map<String, Integer> map = new HashMap<String, Integer>() {
{
put("a", 1);
put("b", 2);
}
};
private static List<String> list = new ArrayList<String>() {
{
add("a");
add("b");
}
};
正例
private static Map<String, Integer> map = new HashMap<>();
static {
map.put("a", 1);
map.put("b", 2);
};
private static List<String> list = new ArrayList<>();
static {
list.add("a");
list.add("b");
};
4.刪除未使用的私有方法和字段
刪除未使用的私有方法和字段,使代碼更簡潔更易維護。若有需要再使用,可以從歷史提交中找回。
反例
public class DoubleDemo1 {
private int unusedField = 100;
private void unusedMethod() {
...
}
public int sum(int a, int b) {
return a + b;
}
}
正例
public class DoubleDemo1 {
public int sum(int a, int b) {
return a + b;
}
}
5.工具類應該屏蔽構造函數
工具類是一堆靜態字段和函數的集合,不應該被實例化。但是,Java 爲每個沒有明確定義構造函數的類添加了一個隱式公有構造函數。所以,爲了避免 java "小白"使用有誤,應該顯式定義私有構造函數來屏蔽這個隱式公有構造函數。
反例
public class MathUtils {
public static final double PI = 3.1415926D;
public static int sum(int a, int b) {
return a + b;
}
}
正例
public class MathUtils {
public static final double PI = 3.1415926D;
private MathUtils() {}
public static int sum(int a, int b) {
return a + b;
}
}
6.公有靜態常量應該通過類訪問
雖然通過類的實例訪問公有靜態常量是允許的,但是容易讓人它誤認爲每個類的實例都有一個公有靜態常量。所以,公有靜態常量應該直接通過類訪問。
反例
public class User {
public static final String CONST_NAME = "name";
...
}
User user = new User();
String nameKey = user.CONST_NAME;
正例
public class User {
public static final String CONST_NAME = "name";
...
}
String nameKey = User.CONST_NAME;
7.不要用NullPointerException判斷空
空指針異常應該用代碼規避(比如檢測不爲空),而不是用捕獲異常的方式處理。
反例
public String getUserName(User user) {
try {
return user.getName();
} catch (NullPointerException e) {
return null;
}
}
正例
public String getUserName(User user) {
if (Objects.isNull(user)) {
return null;
}
return user.getName();
}
8.使用String.valueOf(value)代替""+value
當要把其它對象或類型轉化爲字符串時,使用 String.valueOf(value) 比""+value 的效率更高。
反例
int i = 1;
String s = "" + i;
正例
int i = 1;
String s = String.valueOf(i);
9.過時代碼添加 @Deprecated 註解
當一段代碼過時,但爲了兼容又無法直接刪除,不希望以後有人再使用它時,可以添加 @Deprecated 註解進行標記。在文檔註釋中添加 @deprecated 來進行解釋,並提供可替代方案。
正例
/**
* 保存
*
* @deprecated 此方法效率較低,請使用{@link newSave()}方法替換它
*/
@Deprecated
public void save(){
// do something
};