리스트 프로그래밍(List Programming) – 2. Java로 작성한 리스트 클래스

Copyright (c) 2015-, All Rights Reserved by Kwanghoon Choi
(아래 자바 프로그래밍 강의 교재의 내용을 자유롭게 이용하되 다른 웹 사이트 등을 통한 배포를 금합니다.)

 

2. Java로 작성한 리스트 클래스

정수를 원소로 갖는 리스트를 Java 클래스로 표현해보자. 리스트는 비어 있는 경우이거나 쌍인 경우 두 가지로 분류할 수 있다.

List 클래스를 정의하고 이 클래스를 상속받는 NullList와 Pair 클래스를 정의하는 방식을 사용한다.

먼저 기반 클래스 List는 다음과 같이 정의한다.

class List {
        public boolean isNull() {
                return false;
        }

        public boolean isPair() {
                return false;
        }

        public int first() {
                return 0;
        }

        public List second() {
                return null;
        }

        public String toString() {
                return null;
        }
}

class NullList extends List {
        public boolean isNull() {
                return true;
        }

        public String toString() {
                return "()";
        }
}

class Pair extends List {
        private int firstElem;
        private List secondElem;

        public Pair(int firstElem, List secondElem) {
                this.firstElem = firstElem;
                this.secondElem = secondElem;
        }

        public boolean isPair() {
        return true;
        }

        public int first() {
                return this.firstElem;
        }

        public List second() {
                return this.secondElem;
        }

        public String toString() {
                return "(" + firstElem + ", " + secondElem.toString() + ")";
        }
}

위의 클래스를 사용해서 다음과 같이 리스트 객체를 만들 수 있다.

        List l1 = new NullList();    // 널 리스트
        List l2 = new Pair (3, l1);  // [ 3 ]
        List l3 = new Pair (2, l2);  // [ 2, 3 ]
        List l4 = new Pair (1, l3);  // [ 1, 2, 3 ]

        List l5 = new Pair (1,       // [ 1, 2, 3 ]
                    new Pair (2, 
                      new Pair (3, new NullList() )));

Leave a Reply

Your email address will not be published. Required fields are marked *