배열(Array)

AmeriKano·2023년 3월 15일
0

자료구조

목록 보기
3/5

<배열 노트 정리>

배열에 대해

배열(Array)은 순차적인 메모리에 값을 저장하는 가장 기본적인 자료구조이다. 인덱스(index, 주소)를 이용하여 데이터에 접근하며, 배열의 첫 번째 데이터의 index0임에 유의해야 한다. (음수이거나 선언한 크기를 벗어나는 경우 Java에서는 ArrayIndexOutOfBoundsException 발생.)

배열의 장점

  • index를 이용하여 data에 간단하게 접근 가능

배열의 단점

  • 크기가 고정되어 있음
  • 데이터의 삽입이나 삭제가 비효율적임

JAVA에서의 배열 사용

1차원 배열

int[] array1 = new int[5];		// [0, 0, 0, 0, 0]
int[] array2 = {1, 2, 3, 4, 5};

2차원 배열

int[][] array2D = new int[2][3];	// [[0, 0, 0], [0, 0, 0]]

예시 코드

int[] array = {1, 3, 5, 2, 4};

System.out.println(array[0]);				// 1
System.out.println(array[4]);				// 4
// int a = array[-1];						// 오류
// int b = array[5];						// 오류
  
Arrays.sort(array)							// 오름차순 정렬
System.out.println(array)					// array의 주소 값 출력
// 다음 줄 처럼 작성해야 전체 값 출력 가능
System.out.println(Arrays.toString(array))	// [1, 2, 3, 4, 5]
profile
똑똑한 사람이 되게 해주세요

0개의 댓글