728x90
1.8 Arrays
Single-dimensional Array
선언방법
int [] a = new int[10]; int a[] = new int[10];
초기 값
int,long,float : 0
boolean : false
char : ASCII CODE 0
string, frame : null
ex>
class arNew{
public static void main(String[] args){
int[] a = new int[10];
int b[] = new int[10]l
int i;
for(i=0;i<5;++i){
a[i] = (i+1)*10+1;
b[i] = (i+1)*100 +5;
}
//run-time error
for(i=0;i<15;i++){
System.out.println(a[i]+" "+b[i]);
}
}
}
여기에서 중요한 것이 C언어는 에러가 발생해도 일단 실해하지만 java는 에러가 발생할 경우 에러메시지를 띄어줌
Array value assignment
아래의 방식으로 new를 사용하지 않고도 배열을 생성할 수 있다.int a[]={1,3,5,7,9};
a.length
배열의 길이 반환(number of elements)array copy using assignment(얕은 복사)
b=a;
하지만 이 방식은 새로운 공간을 생성한 것이 아닌 b에다가 a의 메모리 주소를 넘겨준 것이기 때문에 a 배열을 사용하여서 값을 바꾸면 b의 값 역시 함께 바뀌게 됨
class arCopy{
public static void main(String[] args){
int a[] = {11,13,15,17,19,21,23};
int b[] = new int[a.length];
int i;
b=a;
for(i=0;i<a.length;i++){
System.out.println(a[i]+" "+b[i]);
}
}
}
b는 단순히 a의 메모리만을 가리키게 된다.
그렇기에 b에 할당한 메모리 공간은 큰 의미가 없는 것이 된다.
그렇다면 b에 할당한 메모리 공간은 어떻게 될 것인가? JAVA는 이를 자동으로 해제해주는 가비지 컬렉터
이 등장하여 이를 해제해 준다.
- Array Copy using arraycopy()(깊은 복사)
System.arraycopy(srcArray,i,destArray,j,n);
srcArray : 복사될놈
i : 복사될놈 시작 위치
destArray : 복사당할놈
j : 복사당할놈 시작 위치
n : 몇개나 복사할지
ex>
class arCopy{
public static void main(String[] args){
int a[] = {11,13,15,17,19,21,23};
int b[] = new int[a.length];
int i;
System.arraycopy(a,1,b,2,3);
for(i=0;i<a.length;i++){
System.out.println(a[i]+" "+b[i]);
}
}
}
결과물은 a의 1번 위치에서 3개를 골라 b의 2번 위치부터 붙여 넣는다.
Multi-dimensional Array
- Two dimensional Array
int a[][] = new int[3][4];
int[][] a = new int[3][4];
a.length => 3(row) (y축)
a[0].length => 4(column) (x축)
- Value Assignment
int a[][] = {{10,11,12},{20,21,22},{30,31,32},{40,41,42}};
ex>
class arYeeChaWon {
public static void main(String[] args)
{
int a[][] = { {10,11,12},
{20,21,22},
{30,31,32},
{40,41,42} };
int i, j, hab;
System.out.println("a.length : " + a.length);
System.out.println("a[0].length : " + a[0].length + '\n');
for (i=0 ; i<a.length ; i++)
{
hab = 0;
for (j=0 ; j<a[0].length ; j++)
{
System.out.print(a[i][j] + " ");
hab += a[i][j];
}
System.out.print(" " + hab + "\n");
}
}
}
- Three-dimensional Array
boolean[][][] a = new boolean[3][4][5];
int[][][] a = {{{1,2},{3,4}},{{5,6},{7,8}}};
```
728x90
'CS(Computer Science) > 20) 자바' 카테고리의 다른 글
자바를 자바 과제01 (0) | 2020.11.16 |
---|---|
자바를 자바 07 (0) | 2020.11.16 |
자바를 자바 05(String/input,output/Control Flow) (0) | 2020.11.16 |
자바를 자바 04 (0) | 2020.11.16 |
자바를 자바 03 (0) | 2020.11.16 |