Java에서는 Object 클래스의 toString() 메서드를 자유롭게 재정의(오버라이드)할 수 있습니다. 하지만 특정 클래스 타입의 객체 배열을 만들고, 그 배열 자체에 대해 toString() 메서드를 재정의해서 배열의 내용을 한 번에 출력하고 싶은 경우에는 문제가 됩니다. 배열 자체는 toString() 메서드를 재정의할 수 없기 때문에, 현재 Java로는 이를 직접 해결할 방법이 없습니다.
다행히도 다른 방법들을 활용하면 동일한 결과를 얻을 수 있습니다. 아래에서 세 가지 대안을 살펴보겠습니다.
1. Arrays 클래스의 toString() 메서드 활용하기
java.util.Arrays 클래스의 toString() 메서드는 배열(문자열 배열뿐 아니라 모든 타입의 배열)을 인자로 받아 해당 배열의 내용을 문자열로 변환해 반환합니다. 객체 배열을 그대로 이 메서드에 전달하기만 하면 되며, 배열 요소들이 재정의된 toString() 결과와 함께 출력됩니다.
예제 코드
import java.util.Arrays;
class Student {
String name = "Krishna";
int age = 20;
Student(String name, int age) {
this.name = name;
this.age = age;
}
public String toString() {
return "Name: "+this.name+" "+"Age: "+this.age;
}
}
public class Example {
public static void main(String args[]) {
Student std1 = new Student("Krishna", 20);
Student std2 = new Student("Radha", 25);
Student std3 = new Student("Trupthi", 30);
Student std4 = new Student("David", 35);
Student std5 = new Student("Moksha", 40);
Student students[] = {std1, std2, std3, std4, std5};
System.out.println(Arrays.toString(students));
}
}실행 결과
[Name: Krishna Age: 20, Name: Radha Age: 25, Name: Trupthi Age: 30, Name: David Age: 35, Name: Moksha Age: 40]
2. Arrays 클래스의 asList() 메서드 활용하기
asList() 메서드는 배열을 인자로 받아 List 객체로 변환해 반환합니다. List의 toString() 메서드는 각 요소의 toString() 결과를 호출하므로, 이 방법으로도 객체 배열의 내용을 원하는 형식으로 출력할 수 있습니다.
예제 코드
import java.util.Arrays;
class Student {
String name = "Krishna";
int age = 20;
Student(String name, int age) {
this.name = name;
this.age = age;
}
public String toString() {
return "Name: "+this.name+" "+"Age: "+this.age;
}
}
public class Example {
public static void main(String args[]) {
Student std1 = new Student("Krishna", 20);
Student std2 = new Student("Radha", 25);
Student std3 = new Student("Trupthi", 30);
Student std4 = new Student("David", 35);
Student std5 = new Student("Moksha", 40);
Student students[] = {std1, std2, std3, std4, std5};
System.out.println(Arrays.asList(students));
}
}실행 결과
[Name: Krishna Age: 20, Name: Radha Age: 25, Name: Trupthi Age: 30, Name: David Age: 35, Name: Moksha Age: 40]
3. ArrayList 클래스 상속 활용하기
조금 다른 접근 방식이지만 효과적인 해결책입니다. 절차는 다음과 같습니다.
ArrayList 클래스를 상속하는 새로운 클래스를 생성합니다.
이 클래스에 객체들을 추가합니다.
ArrayList가 제공하는 toString() 메서드를 사용해 내용을 출력합니다.
ArrayList의 toString()은 내부적으로 각 요소의 toString()을 호출하므로, Student 클래스에서 재정의한 문자열 형식 그대로 출력됩니다.
예제 코드
import java.util.ArrayList;
import java.util.Arrays;
class Student {
String name = "Krishna";
int age = 20;
Student(String name, int age) {
this.name = name;
this.age = age;
}
public String toString() {
return "Name: "+this.name+" "+"Age: "+this.age;
}
}
public class Example extends ArrayList<Object> {
public static void main(String args[]) {
Example obj = new Example();
obj.add(new Student("Krishna", 20));
obj.add(new Student("Radha", 25));
obj.add(new Student("Trupthi", 30));
obj.add(new Student("David", 35));
obj.add(new Student("Moksha", 40));
System.out.println(obj.toString());
}
}실행 결과
[Name: Krishna Age: 20, Name: Radha Age: 25, Name: Trupthi Age: 30, Name: David Age: 35, Name: Moksha Age: 40]
정리
배열 자체의 toString() 메서드는 재정의할 수 없지만, Arrays.toString(), Arrays.asList(), 또는 ArrayList 상속이라는 세 가지 방법을 통해 객체 배열의 내용을 원하는 형식으로 손쉽게 출력할 수 있습니다. 가장 일반적이고 간단한 방법은 Arrays.toString()을 사용하는 것이며, 컬렉션 기반으로 작업한다면 ArrayList 활용 방법도 좋은 선택입니다.