본문 바로가기

JavaCode(review)

Abstract Class Challenge - interface , linkedList이용

반응형

abstract class - ListItem, - 상속(extends, super)

subClass - Node

interface - NodeList (implement)

 

>ListItem(Abstract class)  - linkedList(another class)  - interface (another class)

          |

 Node(subclass)

 
하단 그림 참조

abstract Class - ListItem

package com.company;
                                //abstract class 'ListItem' = base class
import java.util.ArrayList;
import java.util.List;

public abstract class ListItem {
    protected ListItem rightLink = null;        //reference 
    protected ListItem liftLink = null;		//private이 아닌 protected? > 
						//ba able to access them from our concrete subclass	
    protected Object value ;            //feild

    //constructor
    public ListItem(Object value) {
        this.value = value;
    }

    //abstract methods
    abstract ListItem next();
    abstract ListItem setNext(ListItem item);
    abstract ListItem previous();
    abstract ListItem setPrevious(ListItem item);

    abstract int compareTo(ListItem item);

    //getter
    public Object getValue() {
        return value;
    }
    
    //setter
    public void setValue(Object value) {
        this.value = value;
    }
}

 

Subclass - Node

package com.company;
                                            //Node : subClass
public class Node extends ListItem {        //상속 from Abstract Class
                                            //abstract field와 method in detail해야함.
   //constructor도 super이용해서
   public Node(Object value) {
       super(value);
   }

    //abstract method implement
    @Override
    ListItem next() {
        return this.rightLink;          //from abstract class
    }

    @Override
    ListItem setNext(ListItem item) {
        this.rightLink = item;
        return this.rightLink;          //from abstract class
    }

    @Override
    ListItem previous() {               //from abstract class
        return this.leftLink;
    }

    @Override
    ListItem setPrevious(ListItem item) {       //from abstract class
        this.leftLink = item;
        return this.leftLink;
    }

    @Override
    int compareTo(ListItem item) {
       if(item != null){               // 값이 존재한다면 비교해라. 없으면 -1;
           return ((String) super.getValue()).compareTo((String) item.getValue());
       }else {
           return -1;
       }

    }
}

NodeList (Interface)

package com.company;
                                   //NodeList: interface   //ListItem - abstract class
public interface NodeList {
        ListItem getRoot();         //object
        boolean addItem(ListItem item);          //interface methods
        boolean removeItem(ListItem item);
        void traverse(ListItem root);

}

 

MylinkedList  - 값들 저장 및 알파펫순으로

package com.company;

import java.util.List;          //another class

public class MyLinkedList implements NodeList {      //interface 이용  //ListItem = abstract class
    // a linked list class with new items/ should be inserted

    private ListItem root = null;           //field

    // constructor
    public MyLinkedList(ListItem root) {
        this.root = root;
    }
    // implement methods / interface methods

    @Override
    public ListItem getRoot() {
        return this.root;
    }

    @Override       // add값 알파벳 순으로 저장
    public boolean addItem(ListItem newItem) {
        if (this.root == null) {
            //the list is empty, so newItem becomes root.
            this.root = newItem;
            return true;
        }
        //this. root != null (root 값이 존재할때)
        ListItem currentItem = this.root;
        while (currentItem != null) {     //root가 존재할때 newItem과 비교
            int comparison = (currentItem.compareTo(newItem));
            if (comparison < 0) {
                //newItem이 더 큼/ move right쪽
                if (currentItem.next() != null) { //right 값이 존재할때
                    currentItem = currentItem.next();   //계속 진행  go forward
                } else {
                    // there is no next
                    currentItem.setNext(newItem);        //current , newItem 순
                    newItem.setPrevious(currentItem);
                    //위 두줄 축약형 currentItem.setNext(newItem).setPrevious(currentItem);
                    return true;
                }
            } else if (comparison > 0) {          //newItem is less, move left
                if (currentItem.previous() != null) {      //left 값이 존재할때
                    currentItem.previous().setNext(newItem);
                    newItem.setPrevious(currentItem.previous());
                    newItem.setNext(currentItem);
                    currentItem.setPrevious(newItem);   //previous . newItem . current순

                 //위 4줄 축약형 abbreviate
                // currentItem.previous().setNext(newItem).setPrevious(currentItem.previous());
                //newItem.setNext(currentItem).setPrevious(newItem);
                } else {
                    //previous가 null일때-(root)/ left가 없을때
                    newItem.setNext(this.root);
                    this.root.setPrevious(newItem);         //newItem(root) . current                    this.root = newItem;
                }return true;
            }
        else{
            //equal
            System.out.println(newItem.getValue() + " is already present, not added");
            return false;
        }
    } return false ; // just to fulfill the methods.

}
    @Override
    public boolean removeItem(ListItem item) {
        if(item !=null){
            System.out.println("Delete item "+item.getValue());
        }
        ListItem currentItem = this.root;   //object 설정
        while(currentItem != null){
            int comparison = currentItem.compareTo(item);
            if(comparison == 0){
                // found the item to delete
                if(currentItem == this.root){
                    this.root = currentItem.next();     //point to next
                }
                else{       //previous 값 존재
                    currentItem.previous().setNext(currentItem.next());  //point to next.
                    if(currentItem.next() != null){               //pre    current   next
                        currentItem.next().setPrevious(currentItem.previous());
                    }
                }return true;
            }else if(comparison<0){
                //not reach the point in the linked list
                currentItem = currentItem.next(); //go forward
            }else{
                // comparison >0  // got passed the point
                // the item is not in the list
                return false;
            }

        }
        //we have reached the end of the list
        // without finding the iten to delet
        return false;
    }

    @Override       //List 출력
    public void traverse(ListItem root) {
        if(root == null){
            System.out.println("this list is empty");
        } else{
            while(root != null){
                System.out.println(root.getValue());
                root=root.next();
            }
        }
    }
}

 

Main - print out

 

package com.company;

public class Main {

    public static void main(String[] args) {
	MyLinkedList list = new MyLinkedList(null);     //objcet 설정/call constructor
	list.traverse(list.getRoot());

    String stringData = "Gang,Sang,Jong,Hoo" ;   //string 값 설정.
    String[] data = stringData.split(","); //String[]:string array 설정/ split :문자열 구분
    for(String s : data){                       //반복 for문과 동일 기능
        list.addItem(new Node(s));      // String 값 linkedList에 add
                                                // list.addItem(ListItem newItem)
    }
    list.traverse(list.getRoot());  //list 출력
    list.removeItem(new Node("Jong"));    //list.removeItem(ListItem item)//
    list.traverse(list.getRoot());

    list.removeItem(new Node("Hoo"));
    list.traverse(list.getRoot());              //getter list 출력

    list.removeItem(new Node("Sang"));
    list.traverse(list.getRoot());                  //getter list 출력

    list.removeItem(new Node("Gang"));
    list.traverse(list.getRoot());



    } //main method end

}



Output

D:\IT\JDK\jdk11.0.6_10\bin\java.exe "-javaagent:D:\IT\IDEA\IntelliJ IDEA Community Edition 2020.1\lib\idea_rt.jar=52168:D:\IT\IDEA\IntelliJ IDEA Community Edition 2020.1\bin" -Dfile.encoding=UTF-8 -classpath D:\IT\NewProject\AbstractClassChallenge\out\production\AbstractClassChallenge com.company.Main
this list is empty		//출력	
Gang					//출력
Hoo
Jong
Sang
Delete item Jong
Gang
Hoo
Sang
Delete item Hoo
Gang
Sang
Delete item Sang
Gang							//출력
Delete item Gang
this list is empty				//출력

Process finished with exit code 0