Java ArrayList
1. Collection
- 요소(Element)라고 불리는 가변 개수의 객체들의 집합
- 여러 개의 객체를 보관할 수 있게 만들어진 클래스들의 집합
(기본 타입의 값을 넣으면 자동으로 wrapper 클래스 변환) - 고정 크기의 배열을 다루는 불편함 해소
2. Collection 특징
- 요소의 개수에 따라 자동 크기 조절
- 요소의 추가, 삭제에 따른 요소의 이동을 자동 관리
- Generic 기법으로 구현
클래스 내부에서 사용할 데이터 타입을 외부에서 지정하는 기법
※ generic 기법 예시
3. ArrayList
- ArrayList<자료형> 변수명 = new Array<자료형>();
- java.util.ArrayList 가변 크기 배열을 구현한 클래스
- ArrayList에 객체 삽입과 삭제
리스트의 맨 뒤에 객체 추가 : 공간이 부족하면 자동으로 늘림
리스트의 중간에 객체 삽입 : 삽입된 뒤의 객체는 뒤로 밀림
임의 위치의 객체 삭제 : 객체 삭제 후 자동 자리 이동
메소드 | 설명 |
boolean add(E e) | ArrayList의 맨 뒤에 요소 추가 |
void add(int index, E element) | 지정된 인덱스에 지정된 객체를 삽입 |
void clear() | ArrayList의 모든 요소 삭제 |
E get(int index) | 지정된 인덱스의 요소 반환 |
E remove(int index) | 지정된 인덱스의 요소 삭제 |
boolean remove(Object o) | 지정된 객체와 같은 첫 번째 요소를 ArrayList에서 삭제 |
int size() | ArrayList가 포함하는 요소의 개수 반환 |
▶ 예제 뮤직 플레이리스트 만들기
package onlyPractice;
import java.util.ArrayList;
import java.util.Scanner;
public class MusicPlayList {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ArrayList<String> musicList = new ArrayList<>();
int choice = 0;
while (choice != 4) {
System.out.print("[1]노래추가 [2]노래삭제 [3]노래조회 [4]종료 >> ");
choice = sc.nextInt();
switch (choice) {
case 1: {
System.out.println("=== 현재 재생 목록 ===");
if (musicList.size() == 0) {
System.out.println("재생 목록이 없습니다.");
}
for (int i = 0; i < musicList.size(); i++) {
System.out.println(musicList.get(i));
}
System.out.println("==================");
System.out.print("[1]마지막 위치에 추가 [2]원하는 위치에 추가 >> ");
int num = sc.nextInt();
if (num == 1) {
System.out.print("추가할 노래 입력 >> ");
sc.nextLine();
String addMusic = sc.nextLine();
musicList.add(addMusic);
} else if (num == 2) {
System.out.print("추가할 노래 입력 >> ");
sc.nextLine();
String addMusic = sc.nextLine();
System.out.print("추가할 위치 입력 >> ");
int addMusicIndex = sc.nextInt();
musicList.add(addMusicIndex, addMusic);
}
break;
}
case 2: {
System.out.println("=== 현재 재생 목록 ===");
if (musicList.size() == 0) {
System.out.println("재생 목록이 없습니다.");
}
for (int i = 0; i < musicList.size(); i++) {
System.out.println(musicList.get(i));
}
System.out.println("==================");
System.out.print("[1]선택삭제 [2]전체삭제 >> ");
int remove = sc.nextInt();
if (remove == 1) {
System.out.print("삭제할 노래 선택 >> ");
int removeIndex = sc.nextInt();
musicList.remove(removeIndex);
System.out.println("선택된 노래가 삭제되었습니다.");
} else if (remove == 2) {
musicList.clear();
System.out.println("모든 노래가 삭제되었습니다.");
}
break;
}
case 3: {
System.out.println("=== 현재 재생 목록 ===");
if (musicList.size() == 0) {
System.out.println("재생 목록이 없습니다.");
}
for (int i = 0; i < musicList.size(); i++) {
System.out.println(musicList.get(i));
}
System.out.println("==================");
break;
}
case 4: {
System.out.println("프로그램을 종료합니다.");
break;
}
default: {
}
}
}
}
}
▶ 실습 뮤직 플레이어 만들기
package onlyPractice;
import java.util.ArrayList;
import java.util.Scanner;
public class MusicPlayer {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ArrayList<Music> musicList = new ArrayList<>();
musicList.add(new Music("기억의습작", "김동률", "실제경로/기억의습작.mp3"));
musicList.add(new Music("사랑two", "윤도현", "실제경로/사랑two.mp3"));
musicList.add(new Music("사랑이맞을거야", "윤미래", "실제경로/사랑이맞을거야.mp3"));
musicList.add(new Music("너를만나", "폴킴", "실제경로/너를만나.mp3"));
musicList.add(new Music("마지막사랑", "박기영", "실제경로/마지막사랑.mp3"));
int num = 0;
int musicNum = 0;
while (num != 5) {
System.out.print("[1]노래재생 [2]다음곡 [3]이전곡 [4]정지 [5] >> ");
num = sc.nextInt();
switch (num) {
case 1: {
System.out.println("♬♬♬♬재생중인 노래♬♬♬♬");
System.out.println("노래제목\t\t가수");
System.out.println(musicList.get(musicNum).title + "\t\t" + musicList.get(musicNum).singer);
break;
}
case 2: {
musicNum++;
if (((musicNum) >= musicList.size())) {
System.out.println("다음 곡이 없습니다.");
break;
}
System.out.println("♬♬♬♬재생중인 노래♬♬♬♬");
System.out.println("노래제목\t\t가수");
System.out.println(musicList.get(musicNum).title + "\t\t" + musicList.get(musicNum).singer);
break;
}
case 3: {
musicNum--;
if(musicNum < 0) {
System.out.println("이전 곡이 없습니다.");
break;
}
System.out.println("♬♬♬♬재생중인 노래♬♬♬♬");
System.out.println("노래제목\t\t가수");
System.out.println(musicList.get(musicNum).title + "\t\t" + musicList.get(musicNum).singer);
break;
}
case 4: {
System.out.println("▶▶▶▶▶▶▶노래 정지◀◀◀◀◀◀◀");
break;
}
case 5: {
System.out.println("프로그램을 종료합니다.");
break;
}
default:
}
}
}
}
'Java' 카테고리의 다른 글
자바 추상클래스 (Java abstract class) (0) | 2023.03.05 |
---|---|
자바 상속 (Java Inheritance) (0) | 2023.03.05 |
자바 객체 지향 프로그래밍 OOP (Java Object Oriented Programming) (0) | 2023.01.31 |
자바 메소드(Java Method) (0) | 2023.01.28 |
자바 이차원 배열(Java Two-dimensional array) (0) | 2023.01.22 |
댓글