디버깅을 하면서 리턴받은 배열을 콘솔에 출력하려고 했는데, 다음과 같이 출력되었다.
자바에서는 System.out.println()
로 배열을 바로 출력할 수 없다라는 걸 깨닫고, 출력할 수 있는 여러 방법들을 찾아보았다.
public static void main(String args[]) {
String[] strArray = { "AB", "CD", "EF" };
for(int index = 0; index < strArray.length; index++) {
System.out.print(strArray[index] + " ");
}
}
가장 기본적인 방식이다.
java 1.5버전부터 도입된 방식이다.
python의 for ~ in
과 비슷한 느낌이라 애용하고 있다.
public static void main(String args[]) {
String[] strArray = { "AB", "CD", "EF" };
for(String strValue : strArray) {
System.out.print(strValue + " ");
}
}
Arrays 클래스의 asList 메소드를 사용하면, 배열의 요소에 접근하지 않아도 값을 출력할 수 있다.
asList() 메소드는 매개변수로 받은 배열을 정적 클래스인 ArrayList로 변환하여 반환한다.
public static void main(String args[]) {
String[] strArray = { "AB", "CD", "EF" };
System.out.println(Arrays.asList(strArray));
}
Arrays 클래스의 toString() 메소드에 배열을 전달해 요소를 출력할 수 있다.
asList() 메소드는 배열을 정적 클래스인 ArrayList로 변환해야하는데, toString() 메소드는 변환 작업이 없어 더욱 속도가 빠르다.
public static void main(String args[]) {
String[] strArray = { "AB", "CD", "EF" };
System.out.println(Arrays.toString(strArray));
}
1차원 배열인 경우에는 toString()을 통해 출력할 수 있지만, 다차원의 경우에는 deepToString() 메소드를 사용해주어야 한다.
public static void main(String args[]) {
String[][] strArray = {
{"AA", "AB", "AC"},
{"BA", "BB", "BC"},
{"CA", "CB", "CC"}
};
System.out.println(Arrays.deepToString(strArray));
}
// 결과
[[AA, AB, AC], [BA, BB, BC], [CA, CB, CC]]
java는 Array, List, ArrayList 모두 다르니 리스트로 모두 해결되는 python에 비해 공부해야 할 게 많은 것 같다..
위 방식 중에서는 toString()
이 가장 편할 듯 하니 기억해두자!
(참고한 블로그: https://developer-talk.tistory.com/706)