java實用技巧

1. 需要Map的主鍵和取值時,應該迭代entrySet()

當循環中只需要Map的主鍵時,迭迭代keySet()時正確的。但是,當需要主鍵和取值時,迭代entrySet()纔是更高效的做法,比迭代keySet()後再去get取值性能更佳。

反例:

		Map<String, String> map = ...;
		for (String key : map.keySet()) {
			String valueString = 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()) {
			...
		}

如果還需要檢測null ,可採用:

  • CollectionUtils.isEmpty(collection)
  • CollectionUtils.isNotEmpty(collection)

3.不要把集合對象傳給自己

將集合作爲參數傳遞給集合自己的方法要麼是一個錯誤,要麼是無意義的代碼。
此外,由於某些方法要求參數在執行期間保持不變,因此將集合傳遞給自身可能會導致異常行爲。

反例:

		List<String> list=new ArrayList<String>();
		list.add("hello");
		list.add("world");
		if (list.contains(list)) {//無意義,總返回true
			
		}
		list.remove(list);//性能差,直接使用clear

4.集合初始化儘量指定大小

java 的集合類用起來十分方便,但是看源碼可知,集合也是有大小限制的。每次庫容的時間複雜度很可能是O(n),所以儘量制定可預知的集合大小,能減少集合的擴容次數。

反例:

        int[] arr = new int[] { 1, 2, 3 };
		List<Integer> list2 = new ArrayList<>();
		for (int i : arr) {
			list2.add(i);
		}

正例:

		int[] arr = new int[] { 1, 2, 3 };
		List<Integer> list2 = new ArrayList<>(arr.length);
		for (int i : arr) {
			list2.add(i);
		}

5.頻繁調用Collection.contains方法請使用Set

在java集合類庫中,List的Contains方法普遍時間按複雜度是O(n),如果在代碼中需要頻繁調用contains方法查找數據,可以先將list轉換成HashSet實現,將O(n)的時間複雜度降爲O(1)。

反例:

		List<Integer> list =...;
		for (int i = 0; i < Integer.MAX_VALUE; i++) {
			// 時間複雜度O(n)
			list.contains(i);
		}

正例:

 		List<Integer> list = ...;
		Set<Integer> set=new HashSet<Integer>();
		for (int i = 0; i < Integer.MAX_VALUE; i++) {
			// 時間複雜度O(n)
			set.contains(i);
		}

6. 返回空數組和空集而不是null

返回null,需要調用方強制檢測null,否則就會拋出空指針異常。返回空數組或空集合,有效地避免了調用方因未檢測null而拋出空指針異常。返回空數組或空集合,有效地避免了調用方因未檢測null而拋出空指針異常,還可以刪除調用方檢測null的語句使代碼更簡潔。

反例:

    class Result {

	}

	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 (results != null) {
			for (Result result : resultList) {
                 ...
			}

		}

		Map<String, Result> resultMap = getResultMap();
		if (resultMap != null) {
			for (Map.Entry<String, Result> entry : resultMap.entrySet()) {
                  ...
			}

		}
	}

正例:

    class Result {

	}

	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> entry : resultMap.entrySet()) {

		}
	}

7.List的隨機訪問

數組和鏈表的區別:數組的隨機訪問效率更高。當調用方法獲取到List後,如果想隨機訪問其中的數據,並不知道該數組內部實現是鏈表還是數組,怎麼辦呢?可以判斷它是否實現RandomAccess接口。

正例:

        // 調用別人的服務獲取到list
		List<Integer> list = otherService.getList();
		if (list instanceof RandomAccess) {
			// 內部數組實現,可以隨機訪問
			System.out.println(list.get(list.size() - 1));
		} else {
			// 內部可能是鏈表實現,隨機訪問效率低
		}

8.字符串拼接使用StringBuilder

一般的字符串拼接在編譯期java會進行優化,但是在循環中字符串拼接,java編輯器無法做到優化,所以需要使用StringBuilder進行替換。

反例:

        String string = "";
		for (int i = 0; i < 10; i++) {
			string += 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
		}

9.長整型常量後添加大寫L

在使用長整型常量值時,後面需要添加L,必須是大寫的L,不能是小寫l,小寫l容易跟數字1混淆而造成誤解。

反例:

        long value = 1l;
		long max = Math.max(1L, 6);

正例:

        long value = 1L;
		long max = Math.max(1L, 6L);

10.不要使用魔法值

當你編寫一段代碼時,使用魔法值肯那個看起來很明確,但在調試時它們卻不顯得那麼明確了。這就是爲什麼需要把魔法值定義爲可讀取常量的原因。但是,-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 (a == 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<String, Integer>();
	static {
		map.put("a", 1);
		map.put("b", 2);
	}

	private static List<String> list = new ArrayList<String>();
	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 e2) {
				    ...
				}
			}
		}

	}

正例:

    try (BufferedReader reader = new BufferedReader( new FileReader(fileName))) {
   		String line;
   		while ((line = reader.readLine()) != null) {
   			 ...
   		}
   	} catch (Exception e) {
   		 ...
   	}

工具類應該屏蔽構造函數

工具類是一堆靜態字段函數的集合,不應該被實例化。但是,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 {
		private MathUtils() {}
		
		public static final double PI = 3.1415926D;

		public static int sum(int a, int b) {
			return a + b;
		}
	}

公有靜態常量應該通過類訪問

雖然通過類的實例訪問共有靜態常量是允許的,但是容易讓人誤認爲每個類的實例都有一個共有靜態常量。所以,公有靜態常量應該直接通過類訪問。

反例:

 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;

使用String.valueOf(value)代替""+value

當要把其他對象或類型轉化爲字符串時,使用String.valueOf(value)""+value的效率更高。

反例:

int i = 1;
String s="" + i;

正例:

int i = 1;
String s=String,valueOf(i);

禁止使用構造方法BigDecimal(double)

BigDecimal(double)存在精度損失風險,在精確計算或值比較的場景中可能會導致業務邏輯異常。

反例:

BigDecimal value=new BigDecimal(0.1D);

正例:

BigDecimal value=BigDecimal.valueOf(0.1D);

優先使用常量或確定值來調用equals方法

對象的equals方法容易拋空指針異常,應使用常量或確定有值得對象來調用equals方法。
當然,使用java.util.Objects.equals()方法是最佳實踐。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章