ArrayList의 경우 사용방법이 어렵지 않았고, 이전 챕터의 싱글톤과 연계하는 등의 실습을 직접 진행해 보았음. ArrayList로 무언가를 구현하는 건 그렇게 어렵진 않지만 많은 연습문제를 경험해보는게 좋을 것 같음.
학생 변수 100개 선언 시 일일히 선언하는 것 보다 한번에 선언할 수 있다면?
int[] studentIDs = new int[100];
자바에서는 배열 선언 시 동시에 각 요소의 값이 자동으로 초기화 됨
int[] studentIDs = {1, 2, 3};
System.out.println(studentID[0]);
public class ArrayTest {
public static void main(String[] args) {
char[] alphabets = new char[26];
char ch = 'A';
for (int i = 0; i < 26; i++) {
alphabets[i] = ch++;
}
for (int i = 0; i < 26; i++) {
System.out.println(alphabets[i] + ", " + (int)alphabets[i]);
}
}
}
출력 :
A, 65
B, 66
C, 67
...
Z, 90
책과 그 책을 배열로 가질 library를 만들어 보자.
Book.java
public class Book { private String bookName; private int bookNum; Book() { } Book(String bookName, int bookNum) { this.bookName = bookName; this.bookNum = bookNum; } public void setBookName (String bookName) { this.bookName = bookName; } public String getBookName () { return this.bookName; } public void setBookNum(int bookNum) { this.bookNum = bookNum; } public int getBookNum() { return this.bookNum; } }
BookArrayTest.java
... Book[] library = new Book[5]; for (int i = 0; i < library.length; i++) { System.out.println(library[i]); } ...
출력 :
null
null
null
null
null
인스턴스를 담을 '공간'만 생성되었으므로, 공간 안의 내용은 빈 상태이다. 따라서 우리가 지정해 준 생성자를 통해 내용을 넣을 필요가 있다.
Book.java
... public void showInfo() { System.out.println(bookName + ", " + bookNum); } ...
BookArrayTest.java
Book[] library = new Book[3]; library[0] = new Book("Do It Java Programming", 1); library[1] = new Book("Do It C++ Programming", 2); library[2] = new Book("Do It Python Programming", 3); for (int i = 0; i < library.length; i++) { library[i].showInfo(); }
출력 :
Do It Java Programming, 1
Do It C++ Programming, 2
Do It Python Programming, 3
System.arraycopy() 메서드를 사용하여 값을 복사할 수 있다.
만약 library01, library02가 존재하고 01의 책들을 02로 복사한다고 치자. arraycopy를 사용하는 경우엔 얕은 복사가 발생한다.
따라서 깊은 복사를 시행하고자 하는 경우 for문으로 직접 객체를 순회하며 set 메서드를 사용하여 각 객체에 멤버 변수를 설정해 주어야 한다.
public class EnhancedForLoop {
public static void main(String[] args) {
int[] arr = new int[10];
for (int i = 0; i < 10; i++) {
arr[i] = i;
}
for (int i : arr) {
System.out.println(arr[i]);
}
}
}
이런 식으로 아래의 for문에서는 i에 arr의 각 요소가 대입됨.
이차원 이상으로 구현한 배열
int[][] arr = new arr[행][열];
int[][] arr2d = new int[5][5];
int n = 0;
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
arr2d[i][j] = n++;
}
}
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
System.out.printf("%3d", arr2d[i][j]);
}
System.out.println();
}
출력 :
0 1 2 3 4
5 6 7 8 9
10 11 12 13 14
15 16 17 18 19
20 21 22 23 24
기존 배열은 배열 길이를 나중에 확장하거나 중간에 있는 요소를 비울 수 없지만 ArrayList의 경우에는 가능.
선언
ArrayList<Book> library = new ArrayList<Book>();
나는 여기서 살짝 응용을 해서, 싱글톤을 이용한 팩토리 디자인 패턴으로 ArrayList를 사용해 봤다.
Book.java
public class Book {
private static int bookSerial = 1000;
private int bookNum;
private String bookName;
Book() {
this.bookNum = bookSerial++;
}
public int getBookNum() {
return bookNum;
}
public void setBookNum(int bookNum) {
this.bookNum = bookNum;
}
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public void showInfo() {
System.out.println("번호 : " + this.bookNum + ", 책 이름 : " + bookName);
}
}
BookFactory.java
public class BookFactory {
private static BookFactory instance = new BookFactory();
private BookFactory() {}
public static BookFactory getInstance() {
if (instance == null)
instance = new BookFactory();
return instance;
}
public Book makeNewBook(String bookName) {
Book book = new Book();
book.setBookName(bookName);
return book;
}
}
BookFactoryTest.java
public class BookFactoryTest {
public static void main(String[] args) {
BookFactory bFact = BookFactory.getInstance();
Book[] library = new Book[3];
library[0] = bFact.makeNewBook("김선생의 경제학");
library[1] = bFact.makeNewBook("과식하지 않는 법");
library[2] = bFact.makeNewBook("올바른 수면패턴의 정의");
for (Book book : library) {
book.showInfo();
}
}
}
성적 출력 프로그램을 구현하기.
요구 사항은 아래와 같다.
- Student, Subject 클래스를 각각 선언
- Student 클래스 : 학번, 학생 이름, 수강 과목 목록 포함
- Subject 클래스 : 과목 이름, 과목 점수 포함
Subject.java
public class Subject {
private int subjectScore;
private String subjectName;
Subject() {};
Subject (int subjectScore, String subjectName) {
this.subjectScore = subjectScore;
this.subjectName = subjectName;
}
public void setSubjectScore(int subjectScore) {
this.subjectScore = subjectScore;
}
public int getSubjectScore() {
return this.subjectScore;
}
public void setSubjectName(String subjectName) {
this.subjectName = subjectName;
}
public String getSubjectName() {
return this.subjectName;
}
}
Student.java
import java.util.ArrayList;
public class Student {
private int studentID;
private String studentName;
private ArrayList<Subject> subjectList;
public Student(int studentID, String studentName) {
this.studentID = studentID;
this.studentName = studentName;
subjectList = new ArrayList<Subject>();
}
public void addSubject(int subjectScore, String subjectName) {
Subject sub = new Subject(subjectScore, subjectName);
subjectList.add(sub);
}
public void showStudentInfo() {
int total = 0;
for (Subject s : subjectList) {
total += s.getSubjectScore();
System.out.println("학생 " + studentName + "의 " + s.getSubjectName() + " 과목 성적은 " + s.getSubjectScore() + "입니다.");
}
System.out.println("학생 " + studentName + "의 총점은 " + total + " 입니다.");
}
}
StudentTest.java
public class StudentTest {
public static void main(String[] args) {
Student studentLee = new Student(1001, "Lee");
studentLee.addSubject(85, "선형대수");
studentLee.addSubject(94, "이산수학");
Student studentKim = new Student(1002, "Kim");
studentKim.addSubject(100, "컴퓨터그래픽");
studentKim.addSubject(75, "멀티미디어");
studentKim.addSubject(50, "알고리즘");
studentLee.showStudentInfo();
System.out.println("----------");
studentKim.showStudentInfo();
}
}
출력 :
학생 Lee의 선형대수 과목 성적은 85입니다.
학생 Lee의 이산수학 과목 성적은 94입니다.학생 Lee의 총점은 179 입니다.
학생 Kim의 컴퓨터그래픽 과목 성적은 100입니다.
학생 Kim의 멀티미디어 과목 성적은 75입니다.
학생 Kim의 알고리즘 과목 성적은 50입니다.
학생 Kim의 총점은 225 입니다.