Stack Overflow 擁有海量高質量問答,但尋找最佳實踐仍費時。本文對照 Java API Examples (jExample) 開源代碼庫,為前 10 高票 API 任務提供可直接複製的真實專案片段。
標準寫法
for (String key : map.keySet()) { ... }
jExample 實戰片段(使用 entrySet() 更高效)
for (Entry<BigInteger, R> colie : subMap.entrySet()) {
BigInteger col = colie.getKey();
R vali = colie.getValue();
ret.setVal(row, col, mutr.mutate(vali));
}
三大高票方案:
// 1. Arrays.asList + new ArrayList()
new ArrayList<>(Arrays.asList(array))
// 2. Guava ImmutableList
ImmutableList.of("a", "b")
// 3. Guava Lists.newArrayList
Lists.newArrayList(anotherCollection)
jExample 驗證三者皆廣泛出現於開源專案。
int randomNum = rand.nextInt((max - min) + 1) + min;
int foo = Integer.parseInt("1234");
byte[] bytes = IOUtils.toByteArray(inputStream); // Apache Commons IO
MessageDigest md5 = MessageDigest.getInstance("MD5");
md5.update(inputBytes);
byte[] digest = md5.digest();
// 轉十六進制字串...
// Java 7+ NIO
Files.write(Paths.get("file.txt"),
Arrays.asList("line1", "line2"), StandardCharsets.UTF_8);
// 或 PrintWriter
try (PrintWriter w = new PrintWriter("file.txt", "UTF-8")) {
w.println("line1");
}
String content = new String(Files.readAllBytes(Paths.get("file.txt")), StandardCharsets.UTF_8);
GregorianCalendar gc = new GregorianCalendar();
gc.setTime(date);
XMLGregorianCalendar xmlCal = DatatypeFactory.newInstance().newXMLGregorianCalendar(gc);
StringUtils.isNumeric("23432"); // Apache Commons Lang
開源專案代碼是驗證最佳實踐的金標準;善用 jExample 等搜尋引擎,能以實戰片段取代理論爭論。