在Java編程中,實例相關的常見錯誤主要包括以下幾個方面:
空指針異常(NullPointerException):
String str = null; System.out.println(str.length());
類型轉換異常(ClassCastException):
Object obj = "Hello"; String str = (String) obj;
(假設obj實際上不是字符串)數組越界異常(ArrayIndexOutOfBoundsException):
int[] arr = {1, 2, 3}; System.out.println(arr[3]);
構造函數錯誤:
class MyClass { MyClass(int x) { } } MyClass obj = new MyClass("string");
(構造函數期望一個int參數)初始化塊錯誤:
class MyClass {
static {
int[] arr = new int[5]; // 數組長度為5
arr[10] = 10; // 數組越界
}
}
資源泄漏:
class MyClass {
public void readFile() {
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("file.txt"));
// 讀取文件邏輯
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
多線程問題:
class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
public synchronized int getCount() {
return count;
}
}
class MyThread extends Thread {
private Counter counter;
public MyThread(Counter counter) {
this.counter = counter;
}
@Override
public void run() {
for (int i = 0; i < 1000; i++) {
counter.increment();
}
}
}
public class Main {
public static void main(String[] args) throws InterruptedException {
Counter counter = new Counter();
Thread t1 = new MyThread(counter);
Thread t2 = new MyThread(counter);
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println("Count: " + counter.getCount()); // 可能不是2000
}
}
```(由于線程調度問題,計數可能不是預期的2000)
這些只是Java實例常見錯誤的一部分,實際編程中可能還會遇到更多復雜的問題。通過編寫健壯的代碼、進行充分的測試和使用適當的異常處理機制,可以有效地減少這些錯誤的發生。