在Java中,引用是一種特殊的變量類型,它存儲了另一個對象或變量的內存地址。引用可以用于訪問和操作它們所指向的對象。以下是Java引用的一些常見用法:
// 創建一個String對象
String str = "Hello, World!";
// 創建一個整數數組引用
int[] intArray = {1, 2, 3, 4, 5};
在方法中使用引用作為參數,可以在方法內部修改原始對象的值。
public static void swap(int[] arr, int index1, int index2) {
int temp = arr[index1];
arr[index1] = arr[index2];
arr[index2] = temp;
}
int[] myArray = {1, 2, 3, 4, 5};
swap(myArray, 1, 3);
System.out.println(Arrays.toString(myArray)); // 輸出:[1, 4, 3, 2, 5]
在使用引用之前,檢查它們是否為null,以避免空指針異常。
String str = null;
if (str != null) {
System.out.println(str.length());
} else {
System.out.println("str is null");
}
使用final關鍵字聲明引用,可以防止引用被重新賦值。這對于確保對象不被意外修改非常有用。
final String MY_STRING = "Immutable String";
MY_STRING = "New Value"; // 編譯錯誤:不能修改final變量的值
弱引用允許垃圾回收器在內存不足時回收引用的對象。這在處理緩存等場景中非常有用。
import java.lang.ref.WeakReference;
class MyClass {
private String name;
public MyClass(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
public class WeakReferenceExample {
public static void main(String[] args) {
WeakReference<MyClass> weakRef = new WeakReference<>(new MyClass("Weak Reference Example"));
MyClass obj = weakRef.get();
if (obj != null) {
System.out.println("Object: " + obj.getName());
} else {
System.out.println("Object has been garbage collected.");
}
}
}
這些是Java引用的一些基本用法。了解這些用法可以幫助您更好地管理和操作對象。