본문 바로가기
  • Let's study
BackEnd/Java

[Java] 명언 게시판(1~8단계) - 리스트 버전

by 코딩고수이고파 2026. 7. 20.
 

[Java] 명언 게시판 만들기(6~8단계) - 리팩토링

[Java] 명언 게시판 만들기(6~8단계)[Java] 명언 게시판 만들기(1~5단계) - 리팩토링[Java] 명언 게시판 만들기(1~5단계)요구사항1단계 - 종료2단계 - 등록3단계 - 등록시 생성된 명언번호 노출4단계 - 등록

hyemzzi.tistory.com

이번 리팩토링에서는 명언을 저장하는 자료구조를 배열(Array) 에서 ArrayList로 변경하였다.

배열은 크기가 고정되어 있어 삭제나 추가 시 직접 인덱스를 관리해야 했지만, ArrayList를 사용하면 이러한 작업을 컬렉션이 대신 처리해준다.

1. 배열을 ArrayList로 변경

기존에는 고정 크기의 배열을 사용하였다.

 

WiseSaying[] wiseSayings = new WiseSaying[10];
 

이를 ArrayList로 변경하였다.

 

ArrayList<WiseSaying> wiseSayings = new ArrayList<>();
 

ArrayList는 크기가 자동으로 늘어나므로 배열의 크기를 미리 지정할 필요가 없다.

2. lastIndex 제거

배열을 사용할 때는 현재 저장된 개수를 관리하기 위해 lastIndex가 필요했다.

 

int lastIndex = 0;
 

하지만 ArrayList는 저장된 객체의 개수를 size()로 알 수 있으므로 lastIndex를 더 이상 사용할 필요가 없다.

 

wiseSayings.size();
 

size()는 현재 저장된 명언의 개수를 반환한다.

3. 등록 방식 변경

기존에는 배열의 특정 위치에 직접 저장하였다.

 

wiseSayings[lastIndex++] = wiseSaying;
 

ArrayList에서는 add()를 사용하여 객체를 추가한다.

 

wiseSayings.add(wiseSaying);

 

4. 목록 출력 변경

배열에서는 인덱스로 객체를 가져오지만 ArrayList에서는 get()을 사용한다.

 

WiseSaying target = wiseSayings.get(i);
 

반복문의 종료 조건도 lastIndex 대신 size()를 사용한다.

 

for (int i = wiseSayings.size() - 1; i >= 0; i--)

5. 삭제 기능 개선

배열에서는 삭제 후 빈 공간을 없애기 위해 직접 요소를 앞으로 이동시켰다.

 

for (int i = targetIdx; i < lastIndex - 1; i++) {
    wiseSayings[i] = wiseSayings[i + 1];
}
 

ArrayList에서는 remove() 한 줄로 삭제가 가능하다.

 

wiseSayings.remove(targetIdx);
 

삭제된 뒤의 요소들은 자동으로 한 칸씩 앞으로 이동한다.

6. 수정 기능 변경

수정에서도 get()을 사용하여 객체를 가져온다.

 

WiseSaying w1 = wiseSayings.get(targetIdx);
 

이후 setter를 이용해 내용을 수정한다.

 

w1.setContent(content);
w1.setAuthor(author);

전체 코드

import java.util.ArrayList;
import java.util.Scanner;

public class App {

    Scanner sc = new Scanner(System.in);
    ArrayList<WiseSaying> wiseSayings= new ArrayList<>();
    String cmd = "";
    int lastId = 0; // 가장 최근 생성된 명언 번호

    public void run(){
        System.out.println("== 명언 앱 ==");

        while (!cmd.equals("종료")) {

            System.out.print("명령) ");
            cmd = sc.nextLine();

            if (cmd.equals("등록")) {
                actionWrite();
            } else if (cmd.equals("목록")) {
                actionList();
            } else if(cmd.startsWith("삭제")){
                actionDelete(cmd);
            } else if(cmd.startsWith("수정")){
                actionModify(cmd);
            }
        }
    }

    private void actionList(){
        System.out.println("번호 / 작가 / 명언");
        System.out.println("----------------------");

        for (int i = wiseSayings.size()-1; i >= 0; i--) {
            WiseSaying target=wiseSayings.get(i);

            if (target.getContent().isEmpty())
                continue;

            System.out.println("%d / %s / %s".formatted(target.getId(), target.getAuthor(), target.getContent()));
        }
    }

    private WiseSaying write(String content, String author){
        WiseSaying wiseSaying=new WiseSaying(++lastId, author, content);
        wiseSayings.add(wiseSaying);

        return wiseSaying;
    }

    private void actionWrite(){
        System.out.print("명언: ");
        String content = sc.nextLine();

        System.out.print("작가: ");
        String author = sc.nextLine();

        WiseSaying wiseSaying = write(content, author);

        System.out.println("%d번 명언이 등록되었습니다.".formatted(wiseSaying.getId()));
    }

    private void actionDelete(String cmd){
        //삭제?id=1에서 1만 가져오는 법
        int id = Integer.parseInt(cmd.substring(cmd.indexOf("=")+1).trim());
        int targetIdx=-1;


        for(int i=0;i<wiseSayings.size();i++){
            WiseSaying w1=wiseSayings.get(i);
            if(w1.getId() == id)
                targetIdx=i;
        }

        if(targetIdx==-1) {
            System.out.println("%d번 명언은 존재하지 않습니다.".formatted(id));
            return;
        }

        wiseSayings.remove(targetIdx);

        System.out.println("%d번 명언이 삭제되었습니다.".formatted(id));
    }

    private void actionModify(String cmd) {
        int id = Integer.parseInt(cmd.substring(cmd.indexOf("=")+1).trim());
        int targetIdx=-1;

        for(int i=0;i<wiseSayings.size();i++){
            WiseSaying w1=wiseSayings.get(i);
            if(w1.getId() == id)
                targetIdx=i;
        }

        if(targetIdx==-1) {
            System.out.println("%d번 명언은 존재하지 않습니다.".formatted(id));
            return;
        }

        WiseSaying w1 = wiseSayings.get(targetIdx);

        System.out.println("명언(기존) : %s" .formatted(w1.getContent()));
        System.out.print("명언 : ");
        String content=sc.nextLine();
        w1.setContent(content);

        System.out.println("작가(기존) : %s" .formatted(w1.getAuthor()));
        System.out.print("작가 : ");
        String author = sc.nextLine();
        w1.setAuthor(author);
    }
}

댓글