Java作為一種高級編程語言,其使用廣泛的算法和設計模式,可以大大提高編程效率和代碼質量。下面是Java中常見的算法和設計模式:
1. 排序算法:
public static void bubbleSort(int[] arr) { int n = arr.length; for (int i = 0; i< n - 1; i++) { for (int j = 0; j< n - 1 - i; j++) { if (arr[j] >arr[j + 1]) { int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } }
2. 查找算法:
public static int binarySearch(int[] arr, int key) { int low = 0, high = arr.length - 1; while (low<= high) { int mid = (low + high) / 2; if (arr[mid] == key) { return mid; } if (arr[mid] >key) { high = mid - 1; } else { low = mid + 1; } } return -1; }
3. 設計模式:
工廠模式:
public interface Product{ void show(); } public class ConcreteProduct implements Product{ @Override public void show() { System.out.println("ConcreteProduct"); } } public interface Factory{ public Product create(); } public class ConcreteFactory implements Factory{ @Override public Product create() { return new ConcreteProduct(); } }
單例模式:
public class Singleton { private static Singleton instance = null; private Singleton() {} public static Singleton getInstance() { if (instance == null) { synchronized (Singleton.class) { if (instance == null) { instance = new Singleton(); } } } return instance; } }