- Do it! 자바 프로그래밍 입문 온라인 강의를 수강하며 작성하였습니다.
- Section 1. 자바의 핵심 - 객체지향 프로그래밍
- 20강 "ArrayList 클래스"
- ArrayList 클래스 > 주요 메서드 > 사용 예제
//기본 문법
import java.util.ArrayList;
ArrayList<자료형> 변수명 = new ArrayList<자료형>();
메서드 | 설명 |
---|---|
boolean add(E e) | 요소 하나를 배열에 추가한다. E는 요소의 자료형을 의미한다. |
int size() | 배열에 추가된 요소 전체 개수를 반환한다. |
E get(int index) | 배열의 index 위치에 있는 요소 값을 반환한다. |
E remove(int index) | 배열의 index 위치에 있는 요소 값을 제거하고 그 값을 반환한다. |
boolean isEmpty() | 배열이 비어있는지 확인한다. |
import java.util.ArrayList;
public class BookArrayList {
public static void main(String[] args) {
//ArrayList 선언
ArrayList<Book> library = new ArrayList<Book>();
//add() 메서드로 요소 값 추가
library.add(new Book("태백산맥", "조정래"));
library.add(new Book("데미안", "헤르만 헤세"));
library.add(new Book("어떻게 살 것인가", "유시민"));
library.add(new Book("토지", "박경리"));
library.add(new Book("어린왕지", "생텍쥐페리"));
//배열에 추가된 요소 개수만큼 출력
for(int i=0; i<library.size(); i++) {
Book book = library.get(i);
book.showBookInfo();
}
}
}
위 코드는 Book 클래스를 이용하여 객체 배열을 만들었던 예제(18강. 객체 배열 사용하기)를 ArrayList에 담아본 예제이다.
이것을 응용하여 학생과 과목 객체를 이용한 예제를 만들어보았다.
package arrayList;
public class Subject {
private String name;
private int scorePoint;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getScorePoint() {
return scorePoint;
}
public void setScorePoint(int scorePoint) {
this.scorePoint = scorePoint;
}
}
import java.util.ArrayList;
public class Student {
private static int serialNumber = 1000;
private int studentID;
private String studentName;
private ArrayList<Subject> subjectList;
public Student(String studentName) {
serialNumber++;
studentID = serialNumber;
this.studentName = studentName;
subjectList = new ArrayList<Subject>();
}
public void addSubject(String name, int score) {
Subject subject = new Subject();
subject.setName(name);
subject.setScorePoint(score);
subjectList.add(subject);
}
public void showStudentInfo() {
int total = 0;
for(Subject subject : subjectList) {
total += subject.getScorePoint();
System.out.println(studentName + "님의 " + subject.getName() + " 점수는 " + subject.getScorePoint() + "점 입니다.");
}
System.out.println(studentID + "님의 평균 점수는 " + ((float)total / subjectList.size()) + "점 입니다.");
}
}
package arrayList;
public class StudentTest {
public static void main(String[] args) {
Student studentLee = new Student("Lee");
studentLee.addSubject("국어", 90);
studentLee.addSubject("영어", 95);
studentLee.addSubject("수학", 100);
studentLee.showStudentInfo();
System.out.println("======================");
Student studentKim = new Student("Kim");
studentKim.addSubject("국어", 90);
studentKim.addSubject("영어", 95);
studentKim.addSubject("수학", 100);
studentKim.addSubject("사회", 85);
studentKim.addSubject("과학", 93);
studentKim.showStudentInfo();
}
}