자바에서의 다차원 배열은 배열을 참조하는 참조변수의 배열을 참조변수가 가리키는 방식이다.
코드로 보면 이해가 쉽다.
package test;
import java.util.Arrays;
public class Test {
private static final int COLUMN = 5;
private static final int ROW = 3;
static int num = 0;
public static void main(String[] args) {
// 가변배열 생성
String[][] a = new String[ROW][];
for (int i = 0; i < a.length; i++) {
a[i] = new String[COLUMN - i] ;
for (int j = 0; j < a[i].length; j++) {
a[i][j] = ++num + "";
}
}
System.out.println(Arrays.deepToString(a));
}
}
실행결과
[[1, 2, 3, 4, 5], [6, 7, 8, 9], [10, 11, 12]
가변인자
가변인자는 매개변수의 개수를 동적으로 받을 수 있게 해주는 문법이며 내부적으로 배열을 생성하여 인자를 받는다.
선언방식 : 타입... 변수명
ex) String... name
package test;
import java.util.Arrays;
public class Test {
public static void method(String... strings) {
for(String string : strings) {
System.out.println(string);
}
}
public static void main(String[] args) {
String[] s = {"1", "2", "3"};
Test.method("가", "나", "다");
Test.method(s);
}
main에서 알 수 있듯이 가변인자를 사용한 메서드는 넘길 수 있는 인자의 제한이 없이 내부적으로 배열을 생성하여 받는다. 또한 그렇기 때문에 타입이 일치하는 배열의 참조변수도 인자로 넘길 수 있다.
가변인자를 사용할 때 첫 번째 주의사항은 가변인자를 사용한 메서드를 오버라이딩할 경우 컴파일러가 이를 구분하지 못할 수 있다는 문제점이 있다.
잘못된 코드↓
package test;
import java.util.Arrays;
public class Test {
public static void method(String... strings) {
for(String string : strings) {
System.out.println(string);
}
}
public static void method(String s, String... strings) {
for(String string : strings) {
System.out.println(string);
}
}
public static void main(String[] args) {
String[] s = {"1", "2", "3"};
Test.method("가", "나", "다");
Test.method(s);
}
}
위와 같이 메서드를 오버라이딩할 경우 이러한 오류 메시지가 뜬다.
The method method(String[]) is ambiguous for the type Test
두 번째로는 파라미터로 가변인자를 받을 때 가변인자를 항상 마지막으로 작성해야 한다는 것이다.
이유는 컴파일러가 가변인자의 끝을 구분하지 못하기 때문이다.
잘못된 코드↓
package test;
import java.util.Arrays;
public class Test {
public static void method(String... strings) {
for(String string : strings) {
System.out.println(string);
}
}
public static void method(String... strings, int number) {
for(String string : strings) {
System.out.println(string);
}
}
public static void main(String[] args) {
String[] s = {"1", "2", "3"};
Test.method("가", "나", "다");
Test.method(s);
}
}
그럴 경우 이러한 오류 메시지가 뜬다.
The variable argument type String of the method method must be the last parameter
'Java' 카테고리의 다른 글
추상클래스 (0) | 2023.05.11 |
---|---|
메모리구조(stack, heap, method area) (0) | 2023.05.04 |
arraycopy 메서드를 이용한 배열의 복사 (0) | 2023.04.26 |
for each (0) | 2023.04.25 |
인코딩과 디코딩 (0) | 2023.04.21 |