導讀
java
私慾日生,如地上塵,一日不掃,便又有一層。着實用功,便見道無終窮,愈探愈深,必使精白無一絕不徹方可。
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();
...
}複製代碼
應該使用Collection.isEmpty()檢測空
數組
使用 Collection.size() 來檢測空邏輯上沒有問題,可是使用 Collection.isEmpty()使得代碼更易讀,而且能夠得到更好的性能。任何 Collection.isEmpty() 實現的時間複雜度都是 O(1) ,可是某些 Collection.size() 實現的時間複雜度多是 O(n) 。
安全
反例:
bash
if (collection.size() == 0) {
...
}複製代碼
if (collection.isEmpty()) {
...
}複製代碼
若是須要還須要檢測 null ,可採用CollectionUtils.isEmpty(collection)和CollectionUtils.isNotEmpty(collection)。
app
不要把集合對象傳給本身
dom
List<String> list = new ArrayList<>();
list.add("Hello");
list.add("World");
if (list.containsAll(list)) { // 無心義,老是返回true
...
}
list.removeAll(list); // 性能差, 直接使用clear()複製代碼
集合初始化儘可能指定大小函數
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);
}複製代碼
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
}複製代碼
List 的隨機訪問
工具
// 調用別人的服務獲取到
listList<Integer> list = otherService.getList();
if (list instanceof RandomAccess) {
// 內部數組實現,能夠隨機訪問
System.out.println(list.get(list.size() - 1));
} else {
// 內部多是鏈表實現,隨機訪問效率低
}複製代碼
頻繁調用 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);
}複製代碼
讓代碼更優雅
long value = 1l;
long max = Math.max(1L, 5);複製代碼
long value = 1L;
long max = Math.max(1L, 5L);複製代碼
不要使用魔法值
當你編寫一段代碼時,使用魔法值可能看起來很明確,但在調試時它們卻不顯得那麼明確了。這就是爲何須要把魔法值定義爲可讀取常量的緣由。可是,-一、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) {
...
}複製代碼
不要使用集合實現來賦值靜態成員變量
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");
};複製代碼
建議使用 try-with-resources 語句
Java 7 中引入了 try-with-resources 語句,該語句能保證將相關資源關閉,優於原來的 try-catch-finally 語句,而且使程序代碼更安全更簡潔。
private void handle(String fileName) {
BufferedReader reader = null;
try {
String line;
reader = new BufferedReader(new FileReader(fileName));
while ((line = reader.readLine()) != null) {
...
}
} catch (Exception e) {
...
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
...
}
}
}
}複製代碼
private void handle(String fileName) {
try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
String line;
while ((line = reader.readLine()) != null) {
...
}
} catch (Exception e) {
...
}
}複製代碼
刪除未使用的私有方法和字段
刪除未使用的私有方法和字段,使代碼更簡潔更易維護。如有須要再使用,能夠從歷史提交中找回。
public class DoubleDemo1 {
private int unusedField = 100;
private void unusedMethod() {
...
}
public int sum(int a, int b) {
eturn a + b;
}
}複製代碼
public class DoubleDemo1 {
public int sum(int a, int b) {
return a + b;
}
}複製代碼
刪除未使用的局部變量
刪除未使用的局部變量,使代碼更簡潔更易維護。
public int sum(int a, int b) {
int c = 100;
return a + b;
}複製代碼
public int sum(int a, int b) {
return a + b;
}複製代碼
刪除未使用的方法參數
未使用的方法參數具備誤導性,刪除未使用的方法參數,使代碼更簡潔更易維護。可是,因爲重寫方法是基於父類或接口的方法定義,即使有未使用的方法參數,也是不能刪除的。
public int sum(int a, int b, int c) {
return a + b;
}複製代碼
public int sum(int a, int b) {
return a + b;
}複製代碼
刪除表達式的多餘括號
對應表達式中的多餘括號,有人認爲有助於代碼閱讀,也有人認爲徹底沒有必要。對於一個熟悉 Java 語法的人來講,表達式中的多餘括號反而會讓代碼顯得更繁瑣。
return (x);
return (x + 2);
int x = (y * 3) + 1;
int m = (n * 4 + 2);複製代碼
return x;
return x + 2;
int x = y * 3 + 1;
int m = n * 4 + 2;複製代碼
工具類應該屏蔽構造函數
工具類是一堆靜態字段和函數的集合,不該該被實例化。可是,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;
}
}複製代碼
刪除多餘的異常捕獲並拋出
用 catch 語句捕獲異常後,什麼也不進行處理,就讓異常從新拋出,這跟不捕獲異常的效果同樣,能夠刪除這塊代碼或添加別的處理。
private static String readFile(String fileName) throws IOException {
try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
String line;
StringBuilder builder = new StringBuilder();
while ((line = reader.readLine()) != null) {
builder.append(line);
}
return builder.toString();
} catch (Exception e) {
throw e;
}
}複製代碼
private static String readFile(String fileName) throws IOException {
try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
String line;
StringBuilder builder = new StringBuilder();
while ((line = reader.readLine()) != null) {
builder.append(line);
}
return builder.toString();
}
}複製代碼
公有靜態常量應該經過類訪問
雖然經過類的實例訪問公有靜態常量是容許的,可是容易讓人它誤認爲每一個類的實例都有一個公有靜態常量。因此,公有靜態常量應該直接經過類訪問。
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;複製代碼
不要用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();
}複製代碼
使用String.valueOf(value)代替""+value
當要把其它對象或類型轉化爲字符串時,使用 String.valueOf(value) 比""+value 的效率更高。
int i = 1;
String s = "" + i;複製代碼
int i = 1;
String s = String.valueOf(i);複製代碼
過期代碼添加 @Deprecated 註解
當一段代碼過期,但爲了兼容又沒法直接刪除,不但願之後有人再使用它時,能夠添加 @Deprecated 註解進行標記。在文檔註釋中添加 @deprecated 來進行解釋,並提供可替代方案
/**
* 保存
*
* @deprecated 此方法效率較低,請使用{@link newSave()}方法替換它
*/
@Deprecatedpublic void save(){
// do something
}複製代碼
讓代碼遠離 bug
BigDecimal value = new BigDecimal(0.1D); // 0.100000000000000005551115...複製代碼
BigDecimal value = BigDecimal.valueOf(0.1D);; // 0.1複製代碼
返回空數組和空集合而不是 null
返回 null ,須要調用方強制檢測 null ,不然就會拋出空指針異常。返回空數組或空集合,有效地避免了調用方由於未檢測 null 而拋出空指針異常,還能夠刪除調用方檢測 null 的語句使代碼更簡潔。
反例:
public static Result[] getResults() {
return null;
}
public static List<Result> getResultList() {
return null;
}
public static Map<String, Result> getResultMap() {
return null;}public static void main(String[] args) {
Result[] results = getResults();
if (results != null) {
for (Result result : results) {
... }
}
List<Result> resultList = getResultList();
if (resultList != null) {
for (Result result : resultList) {
...
}
}
Map<String, Result> resultMap = getResultMap();
if (resultMap != null) {
for (Map.Entry<String, Result> resultEntry : resultMap) {
...
}
}
}複製代碼
public static Result[] getResults() {
return new Result[0];
}
public static List<Result> getResultList() {
return Collections.emptyList();
}
public static Map<String, Result> getResultMap() {
return Collections.emptyMap();
}
public static void main(String[] args) {
Result[] results = getResults();
for (Result result : results) {
...
}
List<Result> resultList = getResultList();
for (Result result : resultList) {
...
}
Map<String, Result> resultMap = getResultMap();
for (Map.Entry<String, Result> resultEntry : resultMap) {
...
}
}複製代碼
優先使用常量或肯定值來調用 equals 方法
對象的 equals 方法容易拋空指針異常,應使用常量或肯定有值的對象來調用 equals 方法。固然,使用 java.util.Objects.equals() 方法是最佳實踐。
public void isFinished(OrderStatus status) {
return status.equals(OrderStatus.FINISHED); // 可能拋空指針異常
}複製代碼
public void isFinished(OrderStatus status) {
return OrderStatus.FINISHED.equals(status);
}
public void isFinished(OrderStatus status) {
return Objects.equals(status, OrderStatus.FINISHED);
}複製代碼
枚舉的屬性字段必須是私有不可變
枚舉一般被當作常量使用,若是枚舉中存在公共屬性字段或設置字段方法,那麼這些枚舉常量的屬性很容易被修改。理想狀況下,枚舉中的屬性字段是私有的,並在私有構造函數中賦值,沒有對應的 Setter 方法,最好加上 final 修飾符。
反例:
public enum UserStatus {
DISABLED(0, "禁用"),
ENABLED(1, "啓用");
public int value;
private String description;
private UserStatus(int value, String description) {
this.value = value;
this.description = description;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}複製代碼
正例:
public enum UserStatus {
DISABLED(0, "禁用"),
ENABLED(1, "啓用");
private final int value;
private final String description;
private UserStatus(int value, String description) {
this.value = value;
this.description = description;
}
public int getValue() {
return value;
}
public String getDescription() {
return description;
}
}複製代碼
當心String.split(String regex)
字符串 String 的 split 方法,傳入的分隔字符串是正則表達式!部分關鍵字(好比.[]()\| 等)須要轉義
反例:
"a.ab.abc".split("."); // 結果爲[]
"a|ab|abc".split("|"); // 結果爲["a", "|", "a", "b", "|", "a", "b", "c"]複製代碼
正例:
"a.ab.abc".split("\\."); // 結果爲["a", "ab", "abc"]
"a|ab|abc".split("\\|"); // 結果爲["a", "ab", "abc"]複製代碼
這篇文章,能夠說是從事 Java 開發的經驗總結,分享出來以供你們參考。但願能幫你們避免踩坑,讓代碼更加高效優雅。
本文做者:
王超,花名麟超,阿里巴巴高級地圖技術工程師,一直從事Java研發相關工做。Github id: starcwang