Java Collection Framework

  1. JFC?
    1. Java Collection Framework 란 , Java에서 데이터 저장을 위해서 사용되는 저장객체를 제공하는 프레임 워크로써, Collection interface를 상속받는 List, Set, Map 인터페이스의 구현 집합.

    2. JCF - Generic 타입 제공

      1. Collection <Interface>

        1. List <Interface>

        2. Set < Interface>

      2. Map<K,V>

    3. MUST KNOW JCF

      1. ArrrayList

      2. LinkdedList

      3. Stack

      4. Queue

      5. HashMap

      6. HashSet

      7. PriorityQueue

    4. JCF class

      1. List<E> : 순서가 있으며, 중복허용

        1. Vector<E> : 동기화 보장하는 List Collection.

        2. ArrayList<E> : Vector<E>를 개선한 List Collecton. 동기화 보장이 안되므로 Collections.sysnchronizedList(new ArrayList<E>()) 로 동기화 리스트 생성.

          1. Vector<E> vs ArrayList<E> : Vector 와 ArrayList의 차이는 동기화 여부. 따라서 동기화가 필요하다면, Vector를 사용하는것이 좋다고 판단할 수 있지만, 성능적으로, ArrayList의 동기화 자료구조 (e.g. Collections.sysnchronizedList) 를 사용하여 동기화 리스틀 만드는 것이 좋다.
        3. LinkedList<E> : ArrayList<E>와 달리 메모리 주소값을 기준으로 연결되어 있다. ArrayList<E> 가 배열 기반의 리스트이기 때문에, 무작위 엑세스가 가능한 반면, LinkedList<E>는 순서가 있기 때문에 순차접근이 가능하다.

          1. add(T e)

          2. get(int index)

          3. remove(int index)

          4. isEmpty()

          5. size()

      2. Set<E> : 순서가 없으며, 중복이 허용되지 않는다.

                   인덱스 순서가 없기 때문에, 검색 등이 필요 할 시 전체 컬렉션을 찾는다  
                   검색 시  iterator를 사용한다.  
                   Thread-safe하지 않으므로, 멀티쓰레드 환경에서는 syncronizing해주어야 한다.
        
        1. HashSet<E> : Set implementation class 중 가장 빠르다. Set<E> 의 순서가 정해져 있지 않아, 무작위 접근한다. HashCode(), equals()를 통해 중복유무 비교

        2. LinkedHashSet<E> : HashSet<E>에서 입력된 순서데로 저장. 두번째로 빠르며, HashCode() method로 hash값 저장. equals()로 중복유무 비교.

        3. TreeSet<E> : 오름차순정렬이며, 정렬알고리즘을갖고 있어 느림. 또한 별도의 정렬 알고리즘을 갖고 있음.

      3. Map<K,V> : Key - Value 값으로 이루어진 Collection 자료구조 . 사전과 비슷하며, Key는 중복불가, Value는 중복가능이다.
        순서는 무작위이며, Iterator를 통해 각 원소에 접근 가능. - java.util.HashMap;

        1. HashMap<K, V> :
          1. put(K, V)
          2. get(K)
          3. remove(K)
          4. containsKey(K) -> if(map.containsKey(K))
          5. keySet() - get Key set
  2. MyArrayList.java
package my_arraylist;

import java.util.Arrays;

public class MyArrayList {
    private Object[] initialArr;
    private int current;

    public MyArrayList(){
        // Initial size = 10
        initialArr = new Object[10];
        current = 0;
    }

    public MyArrayList(int n){
        initialArr = new Object[n];
        current = 0;
    }

    public void add(Object n){
        current += 1;
        ensureCapacity(current);

        initialArr[current] = n;
    }

    public void delete(){
        if(current < 0){
            System.out.println("No element exists in array");
            return;
        }
        initialArr[current] = null;
        current -= 1;
    }

    public int length(){return this.initialArr.length;}

    private void ensureCapacity(int current){
        int curCap = this.initialArr.length;
        if(current >= curCap-1){
            // Extend Array
            Object[] oldArr = this.initialArr;
            this.initialArr = Arrays.copyOf(oldArr, this.initialArr.length * 2 + 1);

        }
    }
}

* MyLinkedList.java

package my_linkedlist;

public class MyLinkedList {
    private Node head;
    private Node tail;
    public int size;

    public MyLinkedList(){
        this.head = null;
        this.tail = null;
        this.size = 0;
    }

    public void add(Object value){
        // Create new node
        Node node = new Node(value);

        // Decide first node or not
        if(size == 0 ){
            addAtHead(node);
        }else{
            this.tail.setNextNode(node);
            node.setPrevNode(this.tail);
            node.setNextNode(this.head);
            this.head.setPrevNode(node);
            this.tail = node;
        }
        size++;
    }

    public void addAtHead(Node node){
        this.head = node;
        this.tail = node;
        this.head.setNextNode(tail);
        this.tail.setPrevNode(head);
    }

    public void addAt(int index, Object value){
        // Create new node
        Node node = new Node(value);

        // Get element at specific index
        Node specNode = elementAt(index);

        // Change references
        node.setNextNode(specNode.getNext());
        node.setPrevNode(specNode);

        specNode.setNextNode(node);

        size++;

    }

    public void delete(){
        if(size == 0){
            System.out.println("No node exists to be deleted.");
            return;
        }
        Node node = elementAt(size-1);
        node.getPrev().setNextNode(node.getNext());
        node.getNext().setPrevNode(node.getPrev());

        node.setNextNode(null);
        node.setPrevNode(null);

        size--;
    }


    public Node elementAt(int index){
        if(index > size-1){
            System.out.println("Index is larger than size");
            return null;
        }
        Node returnNode = this.head;
        while(index != 0){
            returnNode = returnNode.getNext();
            index--;
        }
        return returnNode;
    }

    public int length(){return size;}

}

*Node.java

package my_linkedlist;

public class Node {
    private Node next;
    private Node prev;
    private Object value;

    // Default Generator
    protected Node(){
        this.next = null;
        this.prev =null;
        value = null;
    }

    // Generator with value
    protected Node(Object value){
        this.next = null;
        this.prev = null;
        this.value = value;
    }

    // Setters
    protected void setNextNode(Node node){ this.next = node;}
    protected void setPrevNode(Node node){this.prev = node;}

    // Getters
    protected Node getNext() {return next;    }
    protected Node getPrev() {return prev;  }

    // Get Value
    protected Object getValue(){return value.toString();}

    public String  toString(){
        return   value.toString();
    }
}

results matching ""

    No results matching ""