Notice
Recent Posts
Recent Comments
Link
«   2025/12   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

이것저것

Java - 배열 본문

Language/Java

Java - 배열

olivia-com 2021. 7. 15. 23:52

배열 선언

// 형식1
타입[] 변수;

// 형식2
타입 변수[];

타입[] 변수 = null; // 참조할 배열 객체 없는 경우 배열 변수는 null 값으로 초기화

배열 생성

// 1번
타입[] 변수 = {값0, 값1, .. };

// 2번: new 연산자 이용
int[] scores = new int[30];

 

* 배열 변수를 이미 선언한 후에는 다른 실행문에서 중괄호를 사용한 배열 생성이 허용되지 않음!!

타입[] 변수;
변수 = {값0, 값1, .. }; // 컴파일 에러

// 해결 방법: new 연산자 이용
String[] names = null;
names = new String[]{"신용권", "홍길동", "감자바"};

함수 매개변수로 배열 사용하는 경우!

package sec02.exam02;

public class ArrayCreateByValueListExample2 {

	public static void main(String[] args) {
		int[] scores;
		scores = new int[] {83, 90, 87};
		
		int sum1 = 0;
		for(int i = 0; i<3; i++)
			sum1 += scores[i];
		System.out.println("총합: " + sum1);
		
		int sum2 = add( new int[] {83, 90, 87});
		System.out.println("총합: " + sum2);
	}
	
	public static int add(int[] scores) {
		int sum = 0;
		for(int i = 0; i<3; i++)
			sum += scores[i];
		
		return sum;
	}
	

}

>>>
총합: 260
총합: 260

new 연산자로 배열 생성

// 1번
타입[] 변수 = new 타입[길이];

int[] scores = new int[30];
String[] names = new String[30];

int[] array = new int[3];
array[0] = 83;
array[1] = 90;
array[2] = 75;


// 2번
타입[] 변수 = null;
변수 = new 타입[길이];

배열 길이

배열 변수.length;


int[] intArray = {10, 20, 30};
int num = intArray.length; // 3
package sec02.exam04;

public class ArrayLengthExample {

	public static void main(String[] args) {
		int[] scores = {83, 90, 75};
		
		int sum = 0;
		for(int i = 0; i<scores.length; i++)
			sum += scores[i];
		
		System.out.println("총합: " + sum);

	}

}

>>>
총합: 248

다차원 배열

int[][] scores = new int[2][];
scores[0] = new int[2];
scores[1] = new int[3];

scores.length; // 2 (배열A의 길이)
scores[0].length; // 2 (배열 B의 길이)
scores[1].length; // 3 (배열 C의 길이)

int[][] scores = { {95, 88}, {92, 96} };
int score = scores[0][0]; // 95
int score = scores[1][1]; // 96
package sec02.exam06;

public class ArrayInArrayExample {

	public static void main(String[] args) {
		int[][] mathScores = new int[2][3];
		for(int i = 0; i<mathScores.length; i++) { // 2
			for(int k = 0; k<mathScores[i].length; k++) { // 3
				System.out.println("mathScores[" + i + "][" + k + "]=" + mathScores[i][k]);
			}
		}
		System.out.println();
		
		
		int[][] englishScores = new int[2][];
		englishScores[0] = new int[2];
		englishScores[1] = new int[3];
		
		for(int i = 0; i<englishScores.length; i++) {
			for(int k = 0; k<englishScores[i].length; k++) {
				System.out.println("englishScores[" + i + "][" + k + "]=" + englishScores[i][k]);
			}
		}
		System.out.println();
		
		
		int[][] javaScores = { {95, 80}, {92, 96, 80}};
		for(int i = 0; i<javaScores.length; i++) {
			for(int k = 0; k<javaScores[i].length; k++) {
				System.out.println("javaScores[" + i + "][" + k + "]=" + javaScores[i][k]);
			}
		}

	}

}

>>>
mathScores[0][0]=0
mathScores[0][1]=0
mathScores[0][2]=0
mathScores[1][0]=0
mathScores[1][1]=0
mathScores[1][2]=0

englishScores[0][0]=0
englishScores[0][1]=0
englishScores[1][0]=0
englishScores[1][1]=0
englishScores[1][2]=0

javaScores[0][0]=95
javaScores[0][1]=80
javaScores[1][0]=92
javaScores[1][1]=96
javaScores[1][2]=80

객체를 참조하는 배열

package sec02.exam07;

public class ArrayReferenceObjectExample {

	public static void main(String[] args) {
		String[] strArray = new String[3];
		strArray[0] = "Java";
		strArray[1] = "Java";
		strArray[2] = new String("Java");
		
		System.out.println(strArray[0] == strArray[1]); // true
		System.out.println(strArray[0] == strArray[2]); // false
		System.out.println(strArray[0].equals(strArray[2])); // true

	}

}

배열 복사

- for문을 이용해서 요소 하나 하나를 복사

- System.arraycopy()를 이용한 복사

System.arraycopy( Object src(원본 배열), int srcPos(복사 시작할 인덱스), Object dest(복사해 저장할 배열), int destPos(붙일 위치 시작 인덱스), int length(복사할 요소 개수));
package sec02.exam08;

public class ArrayCopyByForExample {

	public static void main(String[] args) {
		int[] oldIntArray = {1, 2, 3};
		int[] newIntArray = new int[5];
		
		for(int i = 0; i<oldIntArray.length; i++)
			newIntArray[i] = oldIntArray[i];
		
		for(int i = 0; i<newIntArray.length; i++)
			System.out.print(newIntArray[i] + ", ");

	}

}

>>>
1, 2, 3, 0, 0,
package sec02.exam09;

public class ArrayCopyExample {

	public static void main(String[] args) {
		String[] oldStrArray = {"java", "array", "copy"};
		String[] newStrArray = new String[5];
		
		System.arraycopy(oldStrArray, 0, newStrArray, 0, oldStrArray.length);
		
		for(int i = 0; i<newStrArray.length; i++)
			System.out.print(newStrArray[i] + ", ");

	}

}

>>>
java, array, copy, null, null,

향상된 for문

for( 타입 변수 : 배열){
	실행문;
}

// 배열의 요소를 차례로 하나씩 꺼내 변수에 저장한 후, 실행문 실행
package sec02.exam10;

public class AdvancedForExample {

	public static void main(String[] args) {
		int[] scores = {95, 71, 84, 93, 87};
		
		int sum = 0;
		for(int score : scores)
			sum += score;
		System.out.println("점수 총합 = " + sum);
		
		double avg = (double)sum / scores.length;
		System.out.println("점수 평균 = " + avg);

	}

}

>>>
점수 총합 = 430
점수 평균 = 86.0