1 / 27

제 3 장 Array 배열

제 3 장 Array 배열. 장성봉. 구구단 예제 프로그램. class GugudanTest { public static void main(String[] args) { for(int i=1;i<=9;i+=3) { System.out.println(" "+i+" DAN "+ (i+1)+" DAN "+(i+2)+" DAN"); for(int j=1;j<=9;j++) {

Download Presentation

제 3 장 Array 배열

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 제 3 장 Array 배열 장성봉

  2. 구구단 예제 프로그램 class GugudanTest { public static void main(String[] args) { for(int i=1;i<=9;i+=3) { System.out.println(" "+i+" DAN "+ (i+1)+" DAN "+(i+2)+" DAN"); for(int j=1;j<=9;j++) { if((i*j) < 10) { System.out.print(i+" * "+j+" = "+(" "+(i*j))); } else { System.out.print(i+" * "+j+" = "+(i*j)); } if(((i+1)*j) < 10) { System.out.print(" "+(i+1)+" * "+j+" = "+(" "+((i+1)*j))); } else { System.out.print(" "+(i+1)+" * "+j+" = "+((i+1)*j)); } if(((i+2)*j) < 10) { System.out.println(" "+(i+2)+" * "+j+" = "+(" "+((i+2)*j))); } else { System.out.println(" "+(i+2)+" * "+j+" = "+((i+2)*j)); } } } } } /* * Results: D:\Java\Exam\02>java GugudanTest 1 DAN 2 DAN 3 DAN 1 * 1 = 1 2 * 1 = 2 3 * 1 = 3 1 * 2 = 2 2 * 2 = 4 3 * 2 = 6 … 7 * 7 = 49 8 * 7 = 56 9 * 7 = 63 7 * 8 = 56 8 * 8 = 64 9 * 8 = 72 7 * 9 = 63 8 * 9 = 72 9 * 9 = 81 D:\Java\Exam\02> */

  3. 배열(Arrary) • 자바에서 배열은 객체이다 • 배열의 선언 • float total[]; or float[] total; • 배열의 생성 • new을 이용한 명시적 방법 • total = new float[5]; • 초기화를 통한 묵시적 방법 • total = {3.0, 4.5, 1.2, 56.0, 0.5}; • length • 배열 생성시 배열의 크기에 대한 정보가 저장됨 • 위 예에서 total.length의 값은 5이다

  4. 배열(Array) • 같은 데이터 타입을 가지는 변수들의 집합 • 같은 이름과 데이터 타입을 갖는 연속적 메모리 위치 • 기본 자료형 혹은 클래스의 객체를 포함할 수 있음. int a, b, c, d, e, f, g, h, i, j; a = 10; b = 10; c = 10; d = 10; e = 10; f = 10; g = 10; h = 10; i = 10; j = 10; int[] a; a = new int[10]; for( int idx = 0; idx < 10; idx++ ) { a[idx] = 10; } a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9] a.length = 10

  5. 배열의 초기화 • 예: int[] k = {1, 2, 3}; • 배열객체가 new연산자를 이용해 생성될 때 0에 해당하는 값으로 초기화됨 • 숫자 : 0 • boolean : false • 문자 : ‘\0’ • 객체 : NULL int[] k; // int[3] k는 오류 k = new int[3]; // k[] = new int[3]은 오류 k[0] = 1; k[1] = 2; k[2] = 3; =

  6. 배열 • 동적으로 생성할 수 있는 클래스이다. • 배열의 한계는 메모리 붕괴나 스택 오버플로우를 막기위해 런타임에 체크됨 • 배열은 선언 만으로 사용 할 수 없다. 선언 후 new연산자를 사용해서 생성한 후 사용해야 한다. • 배열의 선언 만으로는 배열의 사용에 필요한 메모리가 할당 되지 않는다. 배열을 생성( 배열의 크기를 정의)과정을 거쳐야 메모리가 할당된다. • 배열의 크기를 벗어나는 색인은 사용 할 수 없다. • 배열의 선언 • int k[]; // int형의 배열 선언 • int[] k; // int형의 배열 선언

  7. 배열 • 배열 클래스 생성 • k = new int[2]; • int[] k1 = new int[3]; • int[] k2 = {1,2,3} • 배열에 값을 할당 • k[0] = 0; • k[1] = 1; • 할당된 값의 사용 • System.out.println( k[0] );

  8. 배열 public class Ex007Array { public static void main(String[] args) { int[] k; k = new int[2]; //int[] k = new int[2]; //int k[2] ; // error k[0] = 0; k[1] = 1; //k[2] = 2; System.out.println("k[0] = " + k[0]); System.out.println("k[1] = " + k[1]); } }

  9. 기본자료형의 배열 생성 1 int[] arr; // int arr[];와 같음 2 arr = new int[5]; • 자바에서 배열은 동적으로 생성할 • 수 있는 클래스 • 자바에서는 배열을 객체형태로 저장 ① arr ② ② arr[0] arr[1] arr[2] arr[3] arr[4] 1 배열 객체를 가리킬 레퍼런스를 위한 공간이 할당된다. 2힙 영역에서 배열객체를 위한 공간이 할당되고, 그공간을 위한 주소 값이 arr라는 변수의 값으로 들어간다. 1. 배열 객체를 가리킬 레퍼런스변수를 만듬 2. new를 사용해서 실제 배열 객체를 만듬

  10. 배열 k 300 0 1 300 k[0] k[1]

  11. ball[0] [0][0] [0][1] [0][2] [0][3] ball[1] [1][0] [1][1] [1][2] [1][3] ball[2] [2][0] [2][1] [2][2] [2][3] ball[3][4] ball[][] 배열의 배열(2차원 배열) int[][] ball = new int[3][4] int[][] ball = new int[3][]; ball[0] = new int[4]; ball[1] = new int[4]; ball[2] = new int[4];

  12. 다차원 배열-객체 1 String[][] arr; 2 arr = new String[3][]; 3 arr[0] = new int[3]; arr[1] = new int[3]; arr[2] = new int[3]; 4 arr[0][0] = new String(“안녕하세요”); arr[0][1] = new String(“반갑습니다.”); arr[0][2] = new String(“열심히 하세요.”); ② ① ③ arr[0] arr[0][0] Arr[0][1] Arr[0][2] arr arr[1] arr[1][0] Arr[1][1] Arr[1][2] arr[2] Arr[2][0] Arr[2][1] Arr[2][2] String String String

  13. 다차원 배열 • 다차원 배열을 지원하지는 않지만 다차원 배열처럼 사용 할 수 있다. • 다차원 배열을 선언 및 생성 • int[][] k = new int[2][2] • int[][] k = new int[2][]

  14. 다차원 배열 public class Ex008Array { public static void main(String[] args) { int[][] k = new int[2][2]; k[0][0] = 0; k[0][1] = 1; System.out.println("k[0][0] = " + k[0][0]); System.out.println("k[0][1] = " + k[0][1]); } }

  15. 다차원 배열 1000 k 300 0 1 k[0][0] k[0][1] 300 k[0] 2000 1000 0 1 k[1] 2000 k[1][0] k[1][1]

  16. 다차원 배열 public class Ex009Array { public static void main(String[] args) { int[][] k = { {1,2} , {1,2,3} }; System.out.println("k[0][0] = " + k[0][0]); System.out.println("k[0][1] = " + k[0][1]); System.out.println("k[1][2] = " + k[1][2]); } }

  17. 다차원 배열 예제 1publicclass MultiDarray2{ 2 publicstaticvoid main(String[] args){ 3 int ia[][] = { {1, 2}, null }; 4 5 for( int i = 0; i < ia.length; i++ ) 6 for( int j = 0; j < ia[i].length; j++ ) 7 System.out.println(ia[i][j]); 8 } 9 }

  18. 배열의 기타 사항 • 배열이 생성되면 기본 값으로 초기화 된다. 수치 배열이면 0 , boolean 타입이면 false , 문자 타입이면 ‘\u0000’ , 클래스 타입이면 null 로 초기화 된다. • 배열 요소의 크기를 정의 후 , 다시 정의 할 수 있다. 예를 들어 다음과 같이 배열을 정의 한다. int[] a = new int[5]; • 배열을 재 정의 한다. a = new int[10]; • 배열의 크기는 증가 하였으나 처음에 만들어진 배열과는 전혀 다른 새로운 배열이 생성된 것으로 기존 값을 보존 하지 못 한다.

  19. 배열의 길이 배열의 길이는 array 객체의 데이터 멤버인 length를 사용한다. public class Ex010Array { public static void main(String[] args) { int[] k = new int[5]; System.out.println("k.length = " + k.length); } }

  20. 객체 배열 1 String[] arr; // String arr[];와 같음 2 arr = new String[5]; 3 arr[0] = new String(); 4 arr[1] = new String();…. ① arr ② ② arr[0] arr[1] arr[2] arr[3] arr[4] ③ String ③ String String String String 1 배열 객체를 가리킬 레퍼런스를 위한 공간이 할당된다. 2힙 영역에서 배열객체를 위한 공간이 할당되고, 그공간을 위한 주소 값이 arr라는 변수의 값으로 들어간다. 3 배열객체의 각 항목들은 String을 가리킬 레퍼런스이다. 따라서 String객체를 생성하고 레퍼런스가 생성된 String객체를 가리킨다.

  21. 객체배열 예제1 1publicclass ArrayTest{ 2 publicstaticvoid main(String[] args){ 3 String[] arr; 4 arr = new String[3]; 5 6 arr[0] = new String("안녕"); 7 arr[1] = "친구야?"; 8 arr[2] = "반갑다."; 9 10 for(int x = 0; x < arr.length; x++){ 11 System.out.println(arr[x]); 12 } 13 } 14 }

  22. 객체배열 예제2-초기화 1publicclass ObjectArray{ 2 publicstaticvoid main(String[] args){ 3 String[] arr = { new String("Hi "), new String("My "), "name is goopy" }; 4 5 for( int i = 0; i< arr.length; i++ ){ 6 System.out.print(arr[i]); 7 } 8 System.out.println(); 9 } 10 }

  23. 배열 선언 시 주의사항 • 배열명에 직접 배열의 크기를 명시할 수 없다. • double grade[40] = new double[]; // illegal!! • double grade[] = new double[40]; // legal • 다음과 같은 형태로 선언이 가능하다. • double []grade[] = double[3][7]; • double[] []grade = double[3][]; • double grade[][] = double[3][];

  24. System.arraycopy() • System.arraycopy()메소드를 이용하여 배열을 복사 • 다른 방식으로 하는 것보다 훨씬 빠르게 배열을 이동시킬 수 있음 • 기본형의 배열뿐만 아니라 객체 배열에 대해서도 사용가능 • 배열의 일부를 같은 배열의 다른 위치에 이동시킬 수도 있음 Public static void arraycopby( Object Src, int scr_position, Object Dst, int dst_position, int length) => Scr배열의 scr_position위치에서 length만큼의 객체를 Dst배열의 dst_position위치로 이동

  25. 문자열(String) • 배열과 마찬가지로 객체로 취급 • String클래스와 StringBuffer클래스 • String클래스는 읽지전용 • StringBuffer클래스는 읽기/쓰기가 가능하다 • 문자열의 생성 • String str = “good bye”; • String str = new String(“good bye”); • toString() • +, +=시 자동적으로 호출 • 임의의 값을 문자열로 변환하는 메소드이다

  26. String의 변신 class arrayString{ public static void main(String[] args){ int x = 1; String [] names = { "Fred", "Jim", "Sheila" }; names[--x] += "."; for (int i = 0; i < names.length; i++) System.out.println(names[i]); } } 이 프로그램에서 오류가 있으면 올바르게 고치고 예측되는 결과는?

  27. k tmp aclass 복사 a 300 복사 10 300 10 300 msg a 함수 호출 • 자바에서 함수 호출은 call-by-value 방식을 사용 • 함수 호출시, 값을 복사해서 넘겨줌 • 레퍼런스 타입의 인수(클래스, 인터페이스, 배열)인 경우 참조(포인터)를 사용하기 때문에 call-by-reference의 효과가 발생함

More Related