본문 바로가기

프로그래밍/JAVA

[JAVA] 배열(array)

1. 배열(array)


같은 타입의 여러 변수를 하나의 묶음으로 다루는 것을 '배열(array)'이라고 한다.


int[] score = new int[5];



2. 배열의 선언


타입[] 변수이름; 

int[] score;

String[] name;


3. 배열의 생성


배열의 선언 : 배열을 다루기 위한 '참조변수'를 담을 공간이 만들어 짐

배열의 생성 : 데이터를 저장할 수 있는 공간이 만들어짐


ⓘ int [ ] score;


② score = new int [ 5 ] ;


[ new 연산자 ] 에 의해 메모리의 빈 공간에 5개의 int형 데이터를 저장할 수 있는 공간이 생성된다.

[ = 연산자 ] 에 의해 배열의 주소(0x100)가 int형 배열 참조변수 score에 저장된다.

 


4. 배열의 초기화


원하는 값으로 초기화하기 위해서는 아래와 같이 코드를 구성한다.

int[] score = new int[5];
score[0] = 100;
score[1] = 90;
score[2] = 80;
score[3] = 70;
score[4] = 60;


그런데 위에 처럼 하면 불편하니까

① int[] score = { 100, 90, 80, 70, 60};
② int[] score = new int[] { 100, 90, 80, 70, 60 };


이렇게 간략하게 할 수 있다. 그런데 2번보다는 1번의 초기화 방법이 더 편하다.


2번의 방법을 쓰는 경우는 아래 두 가지의 경우이다.


① "선언"과 "초기화"를 따로 해야 하는 경우

int[] score;
score = new int[] { 100, 90, 80, 70, 60 };


② "매개변수"로 배열을 받는 경우 

int add(int[] arr) { /* 내용 생략 */ }
int result = add(new int[] { 100, 90, 80, 70, 60 });



5. 배열의 활용


배열을 다루는데 for문이 필수적으로 활용된다..

int과 float의 계산은 int가 되니까 (float로 형변환을 해줘야 한다.


[ 최대값과 최소값을 구하는 예제 ] 

class exercise
{
public static void main(String[] args){

int[] speed = { 158, 147, 141, 142, 131 };
int max = speed[0];
int min = speed[0];

for(int i = 1 ; i<speed.length; i++){

if( max <= speed[i] ){ // speed[i]가 더 크다면 max = speed[i]
max = speed[i];
}
if ( min > speed[i] ){ // min값이 더 크다면 speed[i]가 더 작은 것이므로                  min = speed[i];   // min = speed[i] 가 된다.                         

}
}
System.out.println("최고구속 : " + max);
System.out.println("최저구속 : " + min);
}
}

최고구속  : 158

최저구속  : 131


[ 배열 요소를 섞는 예제 ] 

class exercise
{
public static void main(String[] args){

int[] number = new int [10];

for(int i=0; i<number.length; i++){
number[i] = i;
System.out.print(number[i]);
}

for(int i=0; i<100; i++){
int n = (int)(Math.random()*10);
int temp = number[0];
number[0] = number[n];
number[n] = temp;
}
System.out.println();

for(int i=0; i<number.length; i++){
System.out.print(number[i]);
}
}
}


[ 로또 번호 출력 ]  배열을 섞는 예제를 응용한다.

class exercise
{
public static void main(String[] args){

int[] lotto = new int[45];

for(int i = 0 ; i<lotto.length; i++){
lotto[i] = i+1;
}

for(int k = 0; k<100; k++){
int n = (int)(Math.random()*45); // 0 <= Math.random() < 1
int temp = lotto[0];
lotto[0] = lotto[n];
lotto[n] = temp;
}

for(int i = 0; i<6 ; i++){
System.out.print(lotto[i] + " ");
}
}
}


[ 버블 정렬 알고리즘 ] 


class exercise
{
public static void main(String[] args){

int[] number = new int[10];

for(int i = 0 ; i<number.length; i++){ // 배열 공간 10개에 0~9까지 임의의 숫자를 담음
System.out.print(number[i] = (int)(Math.random()*10));
}
System.out.println();

for(int i = 0 ; i<number.length; i++){
boolean changed = false;

for(int j = 0; j<number.length-1-i ; j++){
if(number[j] > number[j+1]){ // 오른쪽 값이 더 작으면 자리를 바꿔!
int temp = number[j];
number[j] = number[j+1];
number[j+1] = temp;
changed = true;
}
}

if(!changed) break;

for(int k = 0; k<number.length; k++)
System.out.print(number[k]);
System.out.println();
}
}
}


[ 숫자가 몇 번 출력되는지 계산하는 예제 ] 

class exercise
{
public static void main(String[] args){

int[] number = new int[10];
int[] counter = new int[10];

for(int i = 0 ; i<number.length; i++){
number[i] = (int)(Math.random()*10);
System.out.print(number[i]);
}
System.out.println();

for(int j = 0 ; j<counter.length; j++){
counter[number[j]]++;
}

for(int k = 0 ; k<counter.length; k++){
System.out.println( k + "의 개수 : " + counter[k]);
}
}
}

간략하게 5개 정도로만 표현했다.

0과 5는 한번도 나타나지 않았으므로 counter[0]과 counter[4]는 0이 된다.



6. 다차원 배열


[ 선언 방법 ] 

타입 [ ] [ ] 변수 이름;

 int  [ ] [ ]   score; 

int [] [] score = new int [] [] {
{100, 100, 100},
{90, 90, 90},
{80, 80, 80},
{70, 70, 70},
{60, 60, 60}
}


5x3의 데이터를 담으려고 한다면 int [ ] [ ] score = new int [ 5 ] [ 3 ] 과 같이 하면 된다.


1. 주의할 점은, 2차원 배열은 "배열의 배열"로 구성되어 있다는 것이다.

2. score.length = 5

3. score[0].length = 3 


7. 가변 배열

int [] [] score = new int [5][];
score [0] = new int [4];
score [1] = new int [3];
score [2] = new int [2];
score [3] = new int [2];
score [4] = new int [3];

"열의 개수"를 지정하지 않고, 다양하게 설정해주었다. 이래도 상관없다.


8. 배열의 복사


 [ for문을 이용한 방법 ]

class exercise
{
public static void main(String[] args){

int[] number = {1,2,3,4,5};
int[] newNumber = new int[10];

for(int i=0; i<number.length; i++){
newNumber[i] = number[i]; // 배열 number의 값을 newNumber에 저장한다.
}

for (int i=0; i<newNumber.length; i++)
System.out.print(newNumber[i]);
}
}


[ arraycopy()를 이용한 방법 ]


class exercise
{
public static void main(String[] args){

int[] arr1 = {0, 1, 2, 3, 4};
int[] arr2 = {'A', 'B', 'C', 'D', 'E'};

System.arraycopy(arr1, 0, arr2, 0, arr1.length);

for(int i=0; i<arr2.length; i++){
System.out.println(arr2[i]);
}
}
}

arr1의 [0] 에서 arr2 [0] 으로 arr1.length개의 데이터를 복사한다.









'프로그래밍 > JAVA' 카테고리의 다른 글

[JAVA TIP] 글자크기 바꾸기, 음영처리 바꾸기  (0) 2016.11.01
[JAVA] 제너릭(Generic)  (0) 2016.10.25
[jAVA] 랜덤(Random) 클래스  (0) 2016.09.03
[JAVA] 캘린더(Calendar)  (0) 2016.08.31
[jAVA] 해시맵(HashMap)  (0) 2016.08.31