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

Có thể override toString() cho mảng (array) trong Java?

Không thể. Mảng trong Java là object đặc biệt, không phải class thông thường. Bạn không thể override phương thức toString() của mảng.

Khi in mảng object trực tiếp, kết quả là hashcode (ví dụ: [LStudent;@15db9742).

Các giải pháp thay thế

1. Dùng Arrays.toString() (Khuyên dùng)

import java.util.Arrays;

class Student {
    String name; int age;
    Student(String name, int age) { this.name = name; this.age = age; }
    @Override public String toString() { return "Name: " + name + ", Age: " + age; }
}

public class Example {
    public static void main(String args[]) {
        Student[] students = {
            new Student("Krishna", 20),
            new Student("Radha", 25),
            new Student("Trupthi", 30)
        };
        System.out.println(Arrays.toString(students));
    }
}
[Name: Krishna, Age: 20, Name: Radha, Age: 25, Name: Trupthi, Age: 30]

2. Dùng Arrays.asList()

System.out.println(Arrays.asList(students));
[Name: Krishna, Age: 20, Name: Radha, Age: 25, Name: Trupthi, Age: 30]

3. Kế thừa ArrayList (Custom Collection)

import java.util.ArrayList;

public class StudentList extends ArrayList<Student> {
    // toString() của ArrayList đã in đẹp từng element
}

public class Example {
    public static void main(String args[]) {
        StudentList list = new StudentList();
        list.add(new Student("Krishna", 20));
        list.add(new Student("Radha", 25));
        System.out.println(list); // Tự dùng toString của ArrayList
    }
}

Khuyến nghị: Dùng List<T> (ArrayList) thay vì mảng T[] khi cần in đẹp, thao tác linh hoạt. Mảng chỉ dùng khi cần hiệu suất cực đại hoặc tương tác legacy API.