記錄 Java 基礎核心知識點:hashCode/equals 協議、哈希表原理、I/O 流分類、緩衝機制、文件讀取最佳實踐。
a.equals(b) → a.hashCode() == b.hashCode()Object.hashCode():通常基於對象地址(Native 實現)(n-1) & hashequals() 精確匹配
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
User user = (User) o;
return id == user.id && Objects.equals(name, user.name);
}
@Override
public int hashCode() {
return Objects.hash(id, name); // JDK 7+ 推薦
}
| 維度 | 字節流 | 字符流 |
|---|---|---|
| 基本單位 | Byte (8 bits) | Char (16 bits, UTF-16) |
| 抽象基類 | InputStream / OutputStream | Reader / Writer |
| 處理對象 | 所有數據(圖片、視頻、二進制) | 純文本(需編碼轉換) |
| 轉換橋樑 | InputStreamReader / OutputStreamWriter | 指定 Charset 實現字節↔字符轉換 |
// 無緩衝:每次 1 字節系統調用,極慢
while (in.read() != -1) count++; // 64KB 文件 → 64K 次調用
// 有緩衝:批量讀入內存數組,用戶態拷貝
try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file))) {
byte[] buf = new byte[8192];
int len;
while ((len = bis.read(buf)) != -1) count += len; // 64KB → 8 次調用
}
BufferedReader.readLine() 按行讀取,極大簡化文本處理
// JDK 7+ try-with-resources 確保關閉
public long fileLength(Path path) throws IOException {
try (InputStream in = Files.newInputStream(path)) {
byte[] buf = new byte[8192];
long count = 0;
int len;
while ((len = in.read(buf)) != -1) count += len;
return count;
}
}
// 大文件複製
Files.copy(src, dst, StandardCopyOption.REPLACE_EXISTING);
// 文本逐行處理
Files.lines(path, StandardCharsets.UTF_8)
.filter(line -> !line.startsWith("#"))
.forEach(System.out::println);
new String(bytes) 隱式用平台默認編碼 → 亂碼StandardCharsets.UTF_8Files / Paths (NIO.2) 簡化代碼