Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Cách khởi tạo mảng (array) trong tham số object trong Java

Biến array instance khởi tạo qua constructor hoặc setter method, giống như các field khác.

Cách 1: Khởi tạo qua Constructor

public class Student {
    String name;
    int age;
    String[] subjects; // Array field
    
    // Constructor nhận array
    Student(String name, int age, String[] subjects) {
        this.name = name;
        this.age = age;
        this.subjects = subjects; // Gán reference
    }
    
    void display() {
        System.out.println("Name: " + name);
        System.out.println("Age: " + age);
        System.out.print("Subjects: ");
        for (String s : subjects) System.out.print(s + " ");
        System.out.println();
    }
    
    public static void main(String args[]) {
        String[] subs = {"Mathematics", "English", "Science", "Social"};
        Student obj = new Student("Krishna", 25, subs);
        obj.display();
    }
}
Name: Krishna
Age: 25
Subjects: Mathematics English Science Social

Cách 2: Khởi tạo qua Setter

public class Student {
    String name; int age; String[] subjects;
    
    public void setName(String name) { this.name = name; }
    public void setAge(int age) { this.age = age; }
    public void setSubjects(String[] subjects) { this.subjects = subjects; }
    
    void display() { /* ... */ }
    
    public static void main(String args[]) {
        String[] subs = {"Mathematics", "English", "Science", "Social"};
        Student obj = new Student();
        obj.setName("Krishna");
        obj.setAge(25);
        obj.setSubjects(subs);
        obj.display();
    }
}

Lưu ý quan trọng: Defensive Copy

Array là mutable. Nếu gán trực tiếp reference, caller có thể sửa array từ ngoài → phá vỡ encapsulation.

// Constructor an toàn (defensive copy)
Student(String name, int age, String[] subjects) {
    this.name = name;
    this.age = age;
    this.subjects = subjects != null ? subjects.clone() : new String[0];
}

// Setter an toàn
public void setSubjects(String[] subjects) {
    this.subjects = subjects != null ? subjects.clone() : new String[0];
}

Best practice: Luôn defensive copy cho array/collection mutable trong constructor/setter. Trả về copy trong getter: return subjects.clone();.