1 Chap8: Arrays
2 배열의 종류 같은 자료 형들끼리 모 아둘 수 있는 묶음이 하 나밖에 없는 경우 1 차원 배열이 여러 개 있는 경우 boolean,char, int 등과 같은 기본 자료 형의 배열 객체를 참조하는 참조변수들의 묶음
3 One-Dimensional Arrays Definition: –An array is a data structure that holds some fixed quantity of multiple data items (elements) of the same data type. Arrays are objects, and they are created with the new keyword.
4 One-Dimensional Arrays 배열을 선언하고 생성하는 절차 – 선언과 동시에 생성 가능 int[] numbers = new int[6] – 어떠한 자료의 배열도 생성가능하다. float[] distances = new float[20]; Char[] letters = new char[50]; Date[] dates = new Date[30]; – 배열의 크기를 표시할 때 상수 ( 또는 일반 변수 ) 사용 가능 final int SIZE = 31; int SIZE2=40; double[] temperature = new double[SIZE]; double[] temperature2 = new double[SIZE2]; – 배열은 일단 생성되면 그 크기를 변경할 수 없다.
5 One-Dimensional Arrays [ 주의 ] 배열의 선언시에 크기 지정은 안됨 –int matrix[5]; // 잘못됨 –int matrix[5] = {1,2,3,4,5}; // 잘못됨 배열의 사용 – 다음과 같은 코드에서 int[] numbers = new int[6] – 첫 원소는 numbers[0], 마지막 원소는 numbers[5] – 예 numbers[0] = 0; numbers[3] = 30;
6 One-Dimensional Arrays 또 다른 참조 변수 선언 방법 – 자바에서는 C 언어와 유사하게 배열 참조 변수를 선언할 수 있다. int[] values; // ① 자바 방식 int values[]; // ② C 언어 유사 방식 위 두 가지는 100% 동일 – 여러 개의 배열 변수 선언시 주의 int[] values, grades; // 2 개의 변수 모두 배열로서 선언됨 int values, grades[]; // values 는 int 변수, grades 만 배열 변수 int values[], grades[]; // 2 개의 변수 모두 배열로서 선언됨
7 One-Dimensional Arrays int[] number = new int[6]; int x = 6; number[1] = 7; number[3] = number[x - 5] + 2; int[] s = number; int[] number == a1 : int[6] a int[] number == a1 : int[6] int[] s == a
8 배열 생성 과정 1) 배열 선언 char[] ch; 또는 char ch[]; 2) 배열 생성 ch = new char[4]; 3) 배열 초기화 ch[0]=‘J’; ch[1]=‘a’; ch[2]=‘v’; ch[3]=‘a’;
9 Default Initialization An array of numeric values is initialized with all zero values An array of booleans is initialized with false values An array of objects is initialized to null values, where null means “no value.”
10 More Examples int[] r = new int[6];... r[0] = 1; for ( int i=0; i < r.length-1; i=i+1 ) { r[i+1] = r[i] * 2; } int[] r = new char[]{1,2,4,8,16,32}; int[] r; r = new char[] {1,2,4,8,16,32}; int[] r = {1, 2, 4, 8, 16, 32}; a int[] r == a1 : int[6]
11 More Examples 배열의 크기 for-each 루프 –Java 1.5 부터 지원 – 위 코드는 반복이 진행되면서 첫 번째 원소부터 마지막 원소까지 차례대로 value 에 대입되면서 for 문의 몸체가 수행된다. int[] numbers = new int[100]; for(int i=0; i < numbers.length; i++) numbers[i] = (int)(Math.random()*1000); 배열의 크기는 length 라는 필드로 알 수 있습니다. for (int value: numbers) System.out.println(value);
12 More Examples for~each 활용 예제 – 배열의 모든 원소를 처리하는 경우엔 for ~ each 구문이 좋다. 배열의 크기에 신경쓰지 않아도 되고 인덱스 변수 생성이 필요 없다. –for~each 구문이 적합하지 않은 경우 배열 원소의 값을 변경하는 경우 역순으로 배열 원소를 처리하는 경우 일부 원소만을 출력하는 경우 두 개 이상의 배열을 처리하는 경우 public class Test { public static void main(String[] args) { String[] strings = { "Java", "C", "C++" }; for (String s : strings) System.out.println(s); }
13 Method & Array Arrays can be parameters to methods and can be results from methods. (send the address of the array object) public double[] inverse(double[] r) { int size = r.length; double[] answer = new double[size]; for ( int i = 0; i != size; i = i+1 ) { answer[(size - 1) - i)] = r[i]; } return answer; } double[] d = {2.3, -4.6, 8, 3.14}; double[] e = inverse(d); it is the address of the array (here, the address of the four-element array named by d ) which is bound to the formal parameter, r. Inside the method, a second array is created, and the second array gets copies of the elements in the first array. When the method finishes, it returns as its answer the address of the second array.
14 Method & Array 메소드의 매개 변수로 배열 전달 –call by value 로 처리 – 하지만 주소가 복사되기 때문에 call by reference 효과가 발생
15 Method & Array public class ScoreTest1 { final static int STUDENTS = 5; public static void main(String[] args) { int[] scores = new int[STUDENTS]; getValues(scores); getAverage(scores); } private static void getValues(int[] array) { Scanner scan = new Scanner(System.in); for (int i = 0; i < array.length; i++) { array[i] = i; } private static void getAverage(int[] array) { int total = 0; for (int i = 0; i < array.length; i++) total += array[i]; System.out.println(" 평균은 " + total / array.length + " 입니다 "); }
16 Method & Array 메소드의 반환값으로 배열 전달 – 메소드가 반환값으로 배열을 전달 할 수 있다. – 이 때에도 배열 참조값이 복사됨 import java.util.Scanner; public class Test { public static void main(String[] args) { int[] array; array = getData(); printData(array); } private static int[] getData() { int[] testData = { 10, 20, 30, 40, 50 }; return testData; } private static void printData(int[] array) { for (int i = 0; i < array.length; i++) System.out.println(array[i]); }
17 Array of Object 객체들의 배열에서는 객체에 대한 참조값을 각 원소가 저장 – 배열 객체 생성 newCar[] cars = new Car[6]; – 배열에 객체 할당 cars[0] = new Cars(); cars[1] = new Cars(); –For 루프를 이용한 객체 할당
18 Array of Object (Example) class Car { public int speed // 속도 public int mileage // 주행거리 public String color // 색상 public Car() { speed = mileage = 0; color = "red"; } public void speedUp() { // 속도 증가 메소드 speed += 10; } public String toString() { // 객체의 상태를 문자열로 반환하는 메소드 return " 속도 : " + speed + " 주행거리 : " + mileage + " 색상 : " + color; }
19 Array of Object (Example) public class CarTest { public static void main(String[] args) { final int NUM_CARS = 5; Car[] cars = new Car[NUM_CARS]; for (int i = 0; i < cars.length; i++) { cars[i] = new Car(); cars[i].speedUp(); System.out.println(cars[i]); }
20 Use of Arrays Collecting Input Data within Arrays –Example: Vote Counting (See Figure 8.1, class VoteCounting ) Translation Tables –Example: Substitution Code (See class SubsitutionCode ) Arrays of Objects –Example: Bank Account (See next slide) –An array can be partially filled with objects for ( int i = 0; i != account.length; i = i+1 ) { if ( bank[i] != null ) { System.out.println("Balance of account " + i + " is " + account[i].balanceOf() ); }
21 Use of Arrays (cont’d) BankAccount[] bank = new BankAccount[100]; BankAccount[] bank == a1 : BankAccount[100] a1 null … BankAccount[] bank == a1 : BankAccount[100] a1 nulla2…null bank[1] = new BankAccount(20); a2 : BankAccount int balance == public void deposit(int amount) public boolean withdraw(int amount) 20
22 Case Study: Database What is a database? –a large collection of information. –Ex: a company’s sales records or its customer accounts or its payroll information –in OO terms: a “container” into which objects are inserted, located, and removed. What is a record? –the objects that are stored in a database. –uniquely identified by its key.
23 Build a Database in Java 1.Keys are objects. 2.Records are objects, and a record holds as one of its attributes (the address of) its key object. 3.A database is a kind of “array” of record objects; it must have methods for inserting a record, finding a record, and deleting a record. 4.When the database's user wishes to insert a record into the database, she calls the databases' insert method, supplying the record as the argument; when she wishes to find a record, she calls the find method, supplying a key object as an argument; when she wishes to delete a record, the calls the delete method, supplying a key object as an argument
24
25 Architecture Database Record Key insert find delete getKey(): Key equals(Key y) : boolean 1 *
26 Specification insert(Record r) : boolean Attempts to insert the record, r, into the database. Returns true if the record is successfully added, false otherwise. find(Key k) : Record Attempts to locate the record whose key has value k. If successful, the address of the record is returned, otherwise, null is returned. Methods class Database a container for data items, called Records delete(Key k) : boolean Deletes the record whose key has value k. If successful, true is returned; if no record has key k, false is returned.
27 keyOf(): Key Returns the key that uniquely identifies the record. Methods class Record a data item that can be stored in a database equals(Key m) : boolean Compares itself to another key, m, for equality. If this key and m are same key value, then true is returned; if m is a different key value, then false is returned. lessthan(Key m) : boolean Compares itself to another key, m, for lessthan. If this object's own key is a lesser key value than m, true is returned; otherwise, false is returned. Methods class Key an identification, or “key,” value
28 Implementation class Database (Figure 8.4) class Record (Figure 8.5) for Bank Account class Key (Figure 8.5) for Bank Account class Record (Figure 8.6) for Book class Key (Figure 8.6) for Book
29 Execution Here is a short code fragment that constructs a database for a library and inserts a book into it: Database library = new Database(50000); Record book = new Book( new Key("QA", 76.8), "Charles Dickens", "Great Expectations", 1860 ); library.insert(book); // We might locate the book this way: Key lookup_key = new Key("QA", 76.8); book = library.find(lookup_key); // We can delete the book, if necessary: boolean deleted = library.delete(lookup_key);
30 Case Study: Playing Pieces of Card Games Deck Card new Card() : Card suit count 1*
31 Specification private Card[] deck container for the cards left in the deck newCard(): Card return a card from the deck ; if the deck is empty, return null moreCards(): boolean return true if more cards remain in the deck; return false, otherwise Methods Attributes class CardDeck models a deck of cards private String suit the card's suit, e.g., spades, hearts, diamonds, clubs Attributes class Card models a playing card private int count the card's count, e.g., ace, 2, 3,..., king
32 Implementation class Card (Figure 8.9) class CardDeck (Figure 9.10)
33 static final variable The keyword, final, states that the variable name can not be changed by an assignment; the value is forever constant. The keyword, static, ensures that these variables are unique and not copied as fields into any Card objects that are constructed from class Card. It is traditional to declare static final variables with names that are all upper-case letters.
34 Two-Dimensional Arrays Definition: A two-dimensional array is an array whose elements are arrays. Example: Election int[][] election = new int[3][4]; the length of row : election.length the length of column : election[0].length Candidate Region int[][] election == a1:int[3][] a1 a2 a3 a a2:int[4] a3:int[4] a4:int[4]
35 int[ ][ ] election = new int[3][4]; election[1][3] = election[1][3] + 1; for ( int j = 0; j != 4; j = j+1 ) { int votes = 0; for ( int i = 0; i != 3; i = i+1 ) { votes = votes + election[i][j]; } System.out.println("Candidate " + j + " has “ + votes + " votes"); } for ( int i = 0; i != 3; i = i+1 ) { int total = 0; for ( int j = 0; j != 4; j = j+1 ) { total = total + election[i][j]; } System.out.println(total + " votes were cast in Region " + i); } for ( int i = 0; i != 3; i = i+1 ) { int[] region = election[i]; // region holds the address of a row int total = 0; for ( int j = 0; j != 4; j = j+1 ) { total = total + region[j]; } System.out.println(total + " votes were cast in Region " + i); } Note: we cannot treat a matrix's columns in a similar way.
36 Ragged Array A two-dimensional array can have rows of different lengths Example: int max_words = 20; char[][] word = new char[max_words][]; int count = 0; // how many words are saved in the array boolean processing = true; while ( processing ) { String s = JOptionPane.showInputDialog("Please type a word: "); if ( s.equals("") ) { processing = false; } else { word[count] = new char[ s.length() ]; for ( int i = 0; i != s.length(); i = i+1 ) // first i-1 characters in s are copied into word[line_num] { word[count][i] = s.charAt(i); } count = count + 1; }
37 a1 : char[20][] null 0000 a2 : char[5] null a1 : char[20][] a2 null 0 char[][] word = new char[max_words][] word[line_num] = new char[s.length()]
38 store “bread” into the array ‘b’‘r’‘e’‘a’ a2 : char[5] a1 : char[20][] a2 null ‘d’ store “is” into the array ‘b’‘r’‘e’‘a’ a2 : char[5] a1 : char[20][] a2 a3 null ‘d’ ‘i’‘s’ a3 : char[2] 0 1
39 Case Study: Slide-Puzzle Game 1 * SlidePuzzleBoard PuzzlePieces private PuzzlePiece[][] board move(int w): boolean private int face_value
40 Class Diagram PuzzleController JOptionPane PuzzleWriter PuzzlePieceSlidePuzzleBoard play() private PuzzlePiece[][] board move(int w): boolean private int face_value displayPuzzle() printError(String s) 1*
41 Implementation class PuzzlePiece (Figure 8.12) class SlidePuzzleBoard (Figure 8.13) class PuzzleController (Figure 8.15) class PuzzleWriter (Figure 8.16) class SlidePuzzle (Figure 8.15)