관리 메뉴

Partially Committed

[CH11] Collections framework λ³Έλ¬Έ

πŸ’» Study !/JAVA

[CH11] Collections framework

WonderJay 2022. 8. 27. 16:13
728x90
λ°˜μ‘ν˜•
SMALL

λ³Έ ν¬μŠ€νŒ…μ€ μžλ°”μ˜ 정석 ꡐ재λ₯Ό κ³΅λΆ€ν•˜λ©°, κ°„λ‹¨νžˆ 정리/기둝 μš©λ„λ‘œ μž‘μ„±ν•˜μ˜€μŠ΅λ‹ˆλ‹€. ν˜Ήμ—¬, 잘λͺ»λœ λ‚΄μš©μ΄ μžˆλ‹€λ©΄ μ§€μ ν•΄μ£Όμ‹œλ©΄ κ°μ‚¬ν•˜κ² μŠ΅λ‹ˆλ‹€.

 

 


0. Collections Framework

  Collections Framework λž€ data group 을 닀루고 ν‘œν˜„ν•˜κΈ° μœ„ν•œ λ‹¨μΌν™”λœ architecture 을 λ§ν•œλ‹€. Collections Framework 의 핡심 μΈν„°νŽ˜μ΄μŠ€λŠ” List, Set, Map 이닀. List λŠ” (μˆœμ„œκ°€ μžˆλŠ”) λ°μ΄ν„°μ˜ 쀑볡을 ν—ˆμš©ν•˜λ©° ArrayList, LinkedList, Stack, Vector λ“±μœΌλ‘œ κ΅¬ν˜„λœλ‹€. Set 은 (μˆœμ„œκ°€ μ—†λŠ”) λ°μ΄ν„°μ˜ 쀑볡을 ν—ˆμš©ν•˜μ§€ μ•ŠλŠ” κ²ƒμœΌλ‘œ HashSet, TreeSet λ“±μœΌλ‘œ κ΅¬ν˜„λœλ‹€. Map 은 key - value pair 둜 이뀄진 κ²ƒμœΌλ‘œ μˆœμ„œλŠ” μœ μ§€λ˜μ§€ μ•ŠμœΌλ©° ν‚€λŠ” 쀑볡을 ν—ˆμš©ν•˜μ§€ μ•Šκ³  값은 ν—ˆμš©ν•œλ‹€. HashMap, TreeMap, HashTable, Properties λ“±μœΌλ‘œ κ΅¬ν˜„λœλ‹€.

 

  List μΈν„°νŽ˜μ΄μŠ€λŠ” 쀑볡을 ν—ˆμš©ν•˜λ©΄μ„œ μ €μž₯ μˆœμ„œλŠ” μœ μ§€λ˜λŠ” μ»¬λ ‰μ…˜μ„ κ΅¬ν˜„ν•˜λŠ”λ°μ— μ‚¬μš©ν•œλ‹€. 

https://catsbi.oopy.io/8f0f5192-3a06-405e-8076-dbc5ff9f2dfb

  Set μΈν„°νŽ˜μ΄μŠ€λŠ” 쀑볡을 ν—ˆμš©ν•˜μ§€ μ•Šκ³  μˆœμ„œλ₯Ό κ³ λ €ν•˜μ§€ μ•ŠλŠ” 클래슀λ₯Ό κ΅¬ν˜„ν•˜λŠ”λ°μ— μ‚¬μš©λœλ‹€.

https://catsbi.oopy.io/8f0f5192-3a06-405e-8076-dbc5ff9f2dfb

  Map μΈν„°νŽ˜μ΄μŠ€λŠ” key- value λ₯Ό pair 둜 κ°€μ§€λŠ” 클래슀λ₯Ό κ΅¬ν˜„ν•˜λŠ”λ°μ— μ‚¬μš©λœλ‹€. ν‚€λŠ” 쀑볡될 수 μ—†μœΌλ‚˜ value λŠ” 쀑볡을 ν—ˆμš©ν•˜λ©°, μ€‘λ³΅λœ 킀와 값을 μ €μž₯ν•˜λ©΄ λ§ˆμ§€λ§‰μ— μ €μž₯된 값이 λ‚¨λŠ”λ‹€.

https://catsbi.oopy.io/8f0f5192-3a06-405e-8076-dbc5ff9f2dfb

  Map.Entry μΈν„°νŽ˜μ΄μŠ€λŠ” Map μΈν„°νŽ˜μ΄μŠ€μ˜ λ‚΄λΆ€ μΈν„°νŽ˜μ΄μŠ€(inner interface)이닀. 

 

public interface Map {

...

public static interface Entry{

Object getKey();

Object getValue();

Object setValue(Object value);

boolean equals(Object o);

int hashCode();

...

    }

}

1. ArrayList

  ArrayList λŠ” List μΈν„°νŽ˜μ΄μŠ€μ˜ κ΅¬ν˜„μ΄κΈ° λ•Œλ¬Έμ— λ°μ΄ν„°μ˜ μ €μž₯ μˆœμ„œκ°€ μœ μ§€λ˜κ³  쀑볡을 ν—ˆμš©ν•œλ‹€. Vector 을 κ°œμ„ ν•œ κ²ƒμœΌλ‘œ, 데이터λ₯Ό Object 배열을 μ΄μš©ν•΄μ„œ 순차적으둜 μ €μž₯ν•œλ‹€. 

 

public class ArrayList extends AbstractList implements List, RandomAccess, Cloneable, java.io.Serializable {

...

transient Object[] elementData;

...

}

 

ArrayList λŠ” elementData 을 λ©€λ²„λ³€μˆ˜λ‘œ μ„ μ–Έν•˜κ³  있고, Object λ°°μ—΄μ΄λ―€λ‘œ λͺ¨λ“  type 의 객체λ₯Ό 담을 수 μžˆλ‹€.

import java.util.ArrayList;
import java.util.Collections;

class source{
    public static void main(String[] args) {
        ArrayList list1 = new ArrayList(10);
        list1.add(5);
        list1.add(4);
        list1.add(2);
        list1.add(0);
        list1.add(1);
        list1.add(3);

        ArrayList list2 = new ArrayList(list1.subList(1,4));
        print(list1, list2);

        Collections.sort(list1);
        Collections.sort(list2);

        System.out.println("list1.containsAll(list2): " + list1.containsAll(list2));

        list2.add("B");
        list2.add("C");
        list2.add(3, "A");
        print(list1, list2);

        list2.set(3, "AA");
        print(list1, list2);

        System.out.println("list1.retainAll(list2):" + list1.retainAll(list2));
        print(list1, list2);

        for(int i = list2.size()-1; i>=0 ;i--){
            if(list1.contains(list2.get(i)))
                list2.remove(i);
        }
        print(list1, list2);
    }
    static void print(ArrayList list1, ArrayList list2){
        System.out.println("List1:" + list1);
        System.out.println("List2:" + list2);
        System.out.println();
    }
}
import java.util.ArrayList;
import java.util.List;

class source{
    public static void main(String[] args) {
        final int LIMIT = 10;
        String source = "0123456789abcdefghijABCDEFGHIJ!@#$%^&*()ZZZ";
        int length = source.length();

        List list = new ArrayList(length/LIMIT + 10);

        for(int i=0; i < length; i+=LIMIT){
            if(i+LIMIT < length)
                list.add(source.substring(i, i+LIMIT));
            else
                list.add(source.substring(i));
        }
        for(int i=0; i<list.size(); i++){
            System.out.println(list.get(i));
        }


    }
    static void print(ArrayList list1, ArrayList list2){
        System.out.println("List1:" + list1);
        System.out.println("List2:" + list2);
        System.out.println();
    }
}
import java.util.ArrayList;
import java.util.Vector;

class source{
    public static void main(String[] args) {
        Vector v = new Vector(5);
        v.add("1");
        v.add("2");
        v.add("3");
        print(v);

        v.trimToSize();
        System.out.println("=== After trimToSize() ===");
        print(v);

        v.ensureCapacity(6);
        System.out.println("=== After ensureCapacity(6) ===");
        print(v);

        v.setSize(7);
        System.out.println("=== After setSize(7) ===");;
        print(v);

        v.clear();
        System.out.println("=== After clear() === ");
        print(v);
    }
    static void print(ArrayList list1, ArrayList list2){
        System.out.println("List1:" + list1);
        System.out.println("List2:" + list2);
        System.out.println();
    }
    static void print(Vector v){
        System.out.println(v);
        System.out.println("size :" + v.size());
        System.out.println("capacity :" + v.capacity());
    }
}

3번째 μ½”λ“œμ˜ κ²°κ³ΌλŠ” μ•„λž˜μ™€ κ°™λ‹€.

1. 맨 μ²˜μŒμ—λŠ” capacity κ°€ 5 인 Vector μΈμŠ€ν„΄μŠ€ v λ₯Ό μƒμ„±ν•˜κ³ , 3개의 객체λ₯Ό μ €μž₯ν–ˆκΈ° λ•Œλ¬Έμ— size κ°€ 3, cap 이 5 κ°€ λ‚˜μ˜¨λ‹€.

2. 이후 v.trimToSize(); λ₯Ό ν˜ΈμΆœν•˜λ©΄ 빈 곡간을 μ—†μ• λ―€λ‘œ size = 3, cpa = 3 이 λœλ‹€. 배열은 크기λ₯Ό λ³€κ²½ν•  수 μ—†μœΌλ―€λ‘œ μƒˆλ‘œμš΄ 배열을 μƒμ„±ν•œ λ‹€μŒ μ£Όμ†Œκ°’μ„ λ³€μˆ˜ v 에 ν• λ‹Ήν•˜λŠ” 것이닀. 기쑴의 Vector μΈμŠ€ν„΄μŠ€λŠ” Garbage collector 에 μ˜ν•΄ λ©”λͺ¨λ¦¬μ—μ„œ μ œκ±°λœλ‹€.

3. 그리고 ensureCapacity(6) 을 ν˜ΈμΆœν•˜λ©΄ μΈμŠ€ν„΄μŠ€ v 의 capacity κ°€ μ΅œμ†Œν•œ 6이 λ˜λ„λ‘ ν•œλ‹€. v 의 cap 이 λ§Œμ•½ 6보닀 μ»Έλ‹€λ©΄ μ•„λ¬΄λŸ° λ³€ν™”κ°€ μΌμ–΄λ‚˜μ§€ μ•Šκ³ , 6보닀 μž‘μ•˜λ‹€λ©΄ 크기가 6인 배열을 μƒμ„±ν•΄μ„œ v의 λ‚΄μš©μ„ λ³΅μ‚¬ν•œλ‹€.

4. v.setSize(7) 은 μΈμŠ€ν„΄μŠ€ v 의 size λ₯Ό 7둜 λ§Œλ“€μ–΄μ€€λ‹€. capacity κ°€ μΆ©λΆ„ν•˜λ‹€λ©΄ μƒˆλ‘œμš΄ μΈμŠ€ν„΄μŠ€λ₯Ό λ§Œλ“€μ§€ μ•ŠμœΌλ‚˜, capacity κ°€ λΆ€μ‘±ν•˜λ‹€λ©΄ μƒˆλ‘œμš΄ μΈμŠ€ν„΄μŠ€λ₯Ό μƒμ„±ν•˜λŠ”λ°, λ‚΄λΆ€ κ΅¬ν˜„ 방식에 따라 capacity λŠ” 2λ°°κ°€ λœλ‹€.

5. v.clear(); λŠ” v 의 λͺ¨λ“  μš”μ†Œλ₯Ό μ‚­μ œν•˜λŠ” κ²ƒμœΌλ‘œ size κ°€ 0이 λœλ‹€. 

 

ArrayList λ‚˜ Vecotr 와 같이 배열을 μ΄μš©ν•œ μžλ£Œκ΅¬μ‘°λŠ” λ°μ΄ν„°μ˜ read/write 효울이 쒋은 νŽΈμ΄μ§€λ§Œ,

Capacity λ₯Ό λ³€κ²½ν•΄μ•Ό ν•˜λŠ” μƒν™©μ—λŠ” μƒˆλ‘œμš΄ 배열을 μƒμ„±ν•œ λ‹€μŒμ— λ³΅μ‚¬ν•˜λ―€λ‘œ

효율이 μƒλ‹Ήνžˆ λ–¨μ–΄μ§„λ‹€λŠ” 단점이 μžˆλ‹€.

 

import java.util.List;

public class MyVector implements List{
    Object[] data = null;
    int capacity = 0;
    int size = 0;

    public MyVector(int capacity){
        if(capacity < 0)
            throw new IllegalArgumentException("invalid value. : " + capacity);
        this.capacity = capacity;
        data = new Object[capacity];
    }
    public MyVector(){
        this(10);
    }
    public void ensureCapacity(int minCapacity){
        if(minCapacity - data.length>0)
            setCapacity(minCapacity);
    }
    public boolean add(Object obj){
        ensureCapacity(size+1);
        data[size++] = obj;
        return true;
    }
    public Object get(int index){
        if(index < 0 || index >= size)
            throw new IndexOutOfBoundsException("OutOfBounds...");
        return data[index];
    }
    public Object remove(int index){
        Object oldObj = null;

        if(index < 0 || index >= size)
            throw new IndexOutOfBoundsException("OutOfBounds...");
        oldObj = data[index];

        if(index != size-1){
            System.arraycopy(data, index+1, data, index, size-index-1);
        }
        data[size-1] = null;
        size--;
        return oldObj;
    }
    public boolean remove(Object obj){
        for(int i = 0 ; i < size; i ++){
            if(obj.equals(data[i])){
                remove(i);
                return true;
            }
        }
        return false;
    }
    public void trimToSize(){
        setCapacity(size);
    }
    private void setCapacity(int capacity){
        if(this.capacity == capacity) return;

        Object[] tmp = new Object[capacity];
        System.arraycopy(data, 0, tmp, 0, size);
        data = tmp;
        this.capacity = capacity;
    }
    public Object[] toArray(){
        Object[] result = new Object[size];
        System.arraycopy(data, 0, result, 0, size);

        return result;
    }

    public boolean isEmpty() { return size==0; }
    public int capacity() { return capacity; }
    public int size() { return size; }
    
    public boolean contains(Object o){
        if(indexOf(o) >= 0) return true;
        else return false;
    }
    public Object set(int index, Object element){
        if(index >= size || index < 0)
            throw new IndexOutOfBoundsException();
        else{
            data[index] = element;
            return data;
        }
    }
    public void add(int index, Object element){
        if(index >= size || index < 0)
            throw new IndexOutOfBoundsException();
        else {
            ensureCapacity(size+1);
            data[++size] = element;
        }
    }
    public int indexOf(Object o){
        for(int i = 0 ; i < size; i ++){
            if(data[i].equals(o)){
                return i;
            }
        }
        return -1;
    }
    public int lastIndexOf(Object o){
        for(int i = size - 1 ; i >=0 ; i--){
            if(data[i].equals(o))
                return i;
        }
        return -1;
    }
    public String toString(){
        String str = "[";
        for(int i = 0 ; i < size; i ++){
            str += data[i];
            if(i < size-1){
                str +=",";
            }
        }
        return str + "]";
    }
    /*

    μ΄ν•˜ μƒλž΅

     */
}

 

2. LinkedList

  λ§ν¬λ“œ λ¦¬μŠ€νŠΈλŠ” λ°°μ—΄μ˜ 단점 (1. 크기λ₯Ό λ³€κ²½ν•  수 μ—†λ‹€. 2. λΉ„μˆœμ°¨μ μΈ λ°μ΄ν„°μ˜ μΆ”κ°€/μ‚­μ œμ— λΉ„νš¨μœ¨μ μ΄λ‹€) 을 λ³΄μ™„ν•˜κ³ μž κ³ μ•ˆλœ 자료ꡬ쑰이며 λΆˆμ—°μ†μ μœΌλ‘œ μ‘΄μž¬ν•˜λŠ” 데이터λ₯Ό μ„œλ‘œ linking ν•œ ν˜•νƒœμ΄λ‹€. 각각의 μš”μ†Œλ“€μ€ λ‹€μŒ μš”μ†Œμ— λŒ€ν•œ μ°Έμ‘°(μ£Όμ†Œκ°’)와 λ°μ΄ν„°λ‘œ κ΅¬μ„±λ˜μ–΄μžˆλ‹€.

 

class Node{ 

Node next;

Object obj;

}

 

  λ‹€λ§Œ single linked list λŠ” 이동 λ°©ν–₯이 단방ν–₯이라 λ‹€μŒ μš”μ†Œμ— λŒ€ν•œ 접근은 νš¨μœ¨μ μ΄μ§€λ§Œ 이전 μš”μ†Œμ— λŒ€ν•œ 접근은 μ–΄λ ΅λ‹€. 이λ₯Ό λ³΄μ™„ν•œ 것은 이전 μš”μ†Œμ— λŒ€ν•œ 참쑰도 μ €μž₯ν•˜λŠ” double linked list 이닀.

 

class Node{ 

Node next;

Node previous;

Object obj;

}

 

  double linked list 의 접근성을 보닀 ν–₯상 μ‹œν‚¨ 것은 double circular linked list 으둜 첫 번째 μš”μ†Œμ™€ λ§ˆμ§€λ§‰ μš”μ†Œλ₯Ό μ—°κ²°ν•œ 것이닀. μ‹€μ œ JAVA 의 LinkedList ν΄λž˜μŠ€λŠ” double linked list 둜 κ΅¬ν˜„λ˜μ–΄ μžˆλ‹€. 

 

1. 순차적으둜 μΆ”κ°€/μ‚­μ œ ν•˜λŠ” κ²½μš°μ—λŠ” ArrayList κ°€ LinkedList 보닀 λΉ λ₯΄λ‹€.

2. 쀑간 데이터λ₯Ό μΆ”κ°€/μ‚­μ œ ν•˜λŠ” κ²½μš°μ—λŠ” LinkedList κ°€ ArrayList 보닀 λΉ λ₯΄λ‹€.

3. Stack and Queue

   Stack 은 ArrayList 와 같은 λ°°μ—΄ 기반 μ»¬λ ‰μ…˜ 클래슀둜 κ΅¬ν˜„ν•˜κ³ , Queue λŠ” ArrayList λ₯Ό μ‚¬μš©ν•œλ‹€λ©΄ 데이터λ₯Ό κΊΌλ‚Ό λ•Œλ§ˆλ‹€ 빈 곡간을 μ±„μš°κΈ° μœ„ν•œ λ°μ΄ν„°μ˜ 볡사 μž‘μ—…μ΄ ν•„μš”ν•˜λ―€λ‘œ μ΄λ³΄λ‹€λŠ” LinkedList 둜 κ΅¬ν˜„ν•˜λŠ” 것이 μ ν•©ν•˜λ‹€. 

import java.util.EmptyStackException;
import java.util.Vector;

class MyStack extends Vector {
    public Object push(Object item){
        addElement(item);
        return item;
    }
    public Object pop(){
        Object obj = peek();
        removeElementAt(size()-1);
        return obj;
    }
    public Object peek(){
        int len = size();
        if(len == 0)
            throw new EmptyStackException();
        return elementAt(len-1);
    }
    public boolean empty(){
        return size()==0;
    }
    public int search(Object o){
        int i = lastIndexOf(o);
        if(i>=0)
            return size()-i;
        return -1;
    }
}

μŠ€νƒμ˜ λŒ€ν‘œμ μΈ ν™œμš© μ‚¬λ‘€λŠ” μˆ˜μ‹ 계산, μˆ˜μ‹κ΄„ν˜Έκ²€μ‚¬, μ›Œλ“œν”„λ‘œμ„Έμ„œμ˜ undo/redo, μ›ΉλΈŒλΌμš°μ €μ˜ λ’€λ‘œ/μ•žμœΌλ‘œμ΄λ©°, 큐의 λŒ€ν‘œμ μΈ ν™œμš© μ‚¬λ‘€λŠ” μ΅œκ·Όμ‚¬μš©λ¬Έμ„œ, μΈμ‡„μž‘μ—… λŒ€κΈ°λͺ©λ‘, buffer 등이 μžˆλ‹€.

import java.util.Stack;

class source{
    public static Stack back = new Stack();
    public static Stack forward = new Stack();
    public static void main(String[] args) {
        goURL("1.google");
        goURL("2.naver");
        goURL("3.daum");
        goURL("4.yahoo");

        printStatus();

        goBack();
        System.out.println("push \"go back\" ");
        printStatus();

        goBack();
        System.out.println("push \"go back\" ");
        printStatus();

        goForward();
        System.out.println("push \"go forward\" ");
        printStatus();

        goURL("codechobo.com");
        System.out.println("push \"go to new URL\" ");
        printStatus();
    }
    public static void printStatus(){
        System.out.println("back:"+back);
        System.out.println("forward:"+forward);
        System.out.println("present: " + back.peek());
        System.out.println();
    }
    public static void goURL(String url){
        back.push(url);
        if(!forward.empty())
            forward.clear();
    }
    public static void goForward(){
        if(!forward.empty())
            back.push(forward.pop());
    }
    public static void goBack(){
        if(!back.empty())
            forward.push(back.pop());
    }
}

μœ„ μ˜ˆμ œλŠ” μ›Ή λΈŒλΌμš°μ €μ˜ μ•žμœΌλ‘œκ°€κΈ°, λ’€λ‘œκ°€κΈ°λ₯Ό κ°„λ‹¨νžˆ κ΅¬ν˜„ν•œ κ²ƒμœΌλ‘œ BACK, FORWARD 역할을 ν•˜λŠ” 2 개의 STACK 으둜 κ΅¬ν˜„μ΄ κ°€λŠ₯ν•˜λ‹€.

import java.util.EmptyStackException;
import java.util.Stack;

public class source{
    public static void main(String[] args) {
        Stack st = new Stack();
        String expression = "((2+3)*1)+3";

        System.out.println("Expression:" + expression);

        try{
            for(int i = 0 ; i < expression.length(); i++){
                char ch = expression.charAt(i);
                if(ch=='('){
                    st.push(ch+"");
                } else if(ch==')'){
                    st.pop();
                }
            }
            if(st.isEmpty()){
                System.out.println("correct!");
            }
            else{
                System.out.println("something wrong...");
            }
        } catch (EmptyStackException e){
            System.out.println("something wrong...");
        }
    }
}

μœ„ μ˜ˆμ œλŠ” μˆ˜μ‹μ˜ κ΄„ν˜Έλ₯Ό κ²€μ‚¬ν•˜λŠ” κ²ƒμœΌλ‘œ, stack 을 μ΄μš©ν•˜μ—¬ κ°„λ‹¨νžˆ κ΅¬ν˜„ν•  수 μžˆλ‹€. 

 

import java.util.LinkedList;
import java.util.ListIterator;
import java.util.Queue;
import java.util.Scanner;

class source{
    static Queue q =new LinkedList();
    static final int MAX_SIZE = 5;

    public static void main(String[] args) {
        System.out.println("You can view the guide by typing \"help\". ");

        while(true){
            System.out.print(">>");
            try{
                Scanner s = new Scanner(System.in);
                String input = s.nextLine().trim();

                if("".equals(input)) continue;

                if(input.equalsIgnoreCase("q")){
                    System.exit(0);
                } else if(input.equalsIgnoreCase("help")){
                    System.out.println(" help - Shows guide.");
                    System.out.println(" q or Q - Exit");
                    System.out.println(" history - Shows " + MAX_SIZE + " commands " +
                            "that you have recently entered.");
                } else if(input.equalsIgnoreCase("history")){
                    int i = 0;
                    save(input);
                    LinkedList tmp = (LinkedList)q;
                    ListIterator it = tmp.listIterator();

                    while(it.hasNext())
                        System.out.println(++i+"."+it.next());
                } else{
                    save(input);
                    System.out.println(input);
                }
            } catch (Exception e) {
                System.out.println("invalid command.");
            }
        }
    }
    public static void save(String input){
        if(!"".equals(input))
            q.offer(input); // queue 에 객체λ₯Ό μ €μž₯

        if(q.size() > MAX_SIZE)
            q.remove();
    }
}

μœ„ μ˜ˆμ œλŠ” Queue λ₯Ό μ΄μš©ν•˜μ—¬ μœ λ‹‰μŠ€μ˜ history λͺ…λ Ήμ–΄λ₯Ό κ΅¬ν˜„ν•œ 것이닀.

 

PriorityQueue λŠ” Queue μΈν„°νŽ˜μ΄μŠ€μ˜ κ΅¬ν˜„μ²΄ 쀑 ν•˜λ‚˜λ‘œ, μš°μ„  μˆœμœ„μ— 따라 μ €μž₯λ˜λŠ” queue 이닀. null 은 μ €μž₯ν•  수 μ—†κ³ , μ €μž₯ κ³΅κ°„μœΌλ‘œ 배열을 μ‚¬μš©ν•˜λ©°, 각각의 μš”μ†Œλ₯Ό heap ν˜•νƒœλ‘œ μ €μž₯ν•œλ‹€. heap 은 이진 트리의 ν•œ μ’…λ₯˜λ‘œ max κ°’μ΄λ‚˜ min 값을 효율적으둜 찾을 수 μžˆλ‹€.

Deque(Double-Ended Queue) λŠ” μ–‘λ°©ν–₯ Queue 이닀.

4. Interator, ListIterator, Enumeration

  μ»¬λ ‰μ…˜μ— μ €μž₯된 μš”μ†Œλ₯Ό μ ‘κ·Όν•˜λŠ”λ°μ— μ‚¬μš©ν•˜λŠ” μΈν„°νŽ˜μ΄μŠ€μ΄λ‹€. Enumeration 은 Iterator 의 ꡬ버전이고, ListIterator 은 Iterator 을 보닀 κ°œμ„ ν•œ 것이닀.

 

  Collections framework μ—λŠ” Iterator μΈν„°νŽ˜μ΄μŠ€λ‘œ μ €μž₯된 μš”μ†Œλ₯Ό μ½μ–΄μ˜€λŠ” 방법을 ν‘œμ€€ν™”ν•˜μ˜€λ‹€.

 

public interface Iterator{

boolean hasNext();

Object next();

void remove();

}

 

map μΈν„°νŽ˜μ΄μŠ€λ₯Ό κ΅¬ν˜„ν•œ Collection class λŠ” key-value λ₯Ό pair 둜 μ €μž₯ν•˜κΈ° λ•Œλ¬Έμ— iterator 을 직접 ν˜ΈμΆœν•  수 μ—†λ‹€. λŒ€μ‹  keySet() μ΄λ‚˜ entrySet() λ©”μ„œλ“œλ₯Ό μ΄μš©ν•˜μ—¬ key 와 value λ₯Ό 각각 set 의 ν˜•νƒœλ‘œ μ–»μ–΄μ˜¨ 뒀에 iterator λ₯Ό ν˜ΈμΆœν•˜λŠ” 것이 κ°€λŠ₯ν•˜λ‹€.

import java.util.ArrayList;
import java.util.Iterator;

class source{
    public static void main(String[] args) {
        ArrayList list = new ArrayList();
        list.add("1");
        list.add("2");
        list.add("3");
        list.add("4");
        list.add("5");

        Iterator it = list.iterator();

        while(it.hasNext()){
            Object obj = it.next();
            System.out.println(obj);
        }
    }
}

ListIterator 은 단방ν–₯ 순회만 κ°€λŠ₯ν•œ Iterator 을 κ°œμ„ ν•˜μ—¬ μ–‘λ°©ν–₯ μˆœνšŒκ°€ κ°€λŠ₯ν•œλ° λ‹€λ§Œ ArrayList λ‚˜ LinkedList 처럼 List μΈν„°νŽ˜μ΄μŠ€λ₯Ό κ΅¬ν˜„ν•œ μ»¬λ ‰μ…˜μ— λŒ€ν•΄μ„œλ§Œ μ‚¬μš©μ΄ κ°€λŠ₯ν•˜λ‹€. 

import java.util.ArrayList;
import java.util.ListIterator;

class source{
    public static void main(String[] args) {
        ArrayList list = new ArrayList();
        list.add("1");
        list.add("2");
        list.add("3");
        list.add("4");

        ListIterator it = list.listIterator();

        while(it.hasNext()){
            System.out.println(it.next());
        }
        System.out.println();

        while(it.hasPrevious()){
            System.out.println(it.previous());
        }
        System.out.println();
    }
}
import java.util.ArrayList;
import java.util.Iterator;

public class source{
    public static void main(String[] args) {
        ArrayList original = new ArrayList(10);
        ArrayList copy1 = new ArrayList(10);
        ArrayList copy2 = new ArrayList(10);

        for(int i=0; i<10; i++)
            original.add(i+"");
        Iterator it = original.iterator();

        while(it.hasNext())
            copy1.add(it.next());

        System.out.println("= copy from Original to copy1 =");
        System.out.println("original:" + original);
        System.out.println("copy1:" + copy1);
        System.out.println();

        it = original.iterator();

        while(it.hasNext()){
            copy2.add(it.next());
            it.remove();
        }

        System.out.println("= move from original to copy2 = ");
        System.out.println("original:" + original);
        System.out.println("copy2:" + copy2);
    }
}

iterator 의 remove() λŠ” νŠΉμ • μœ„μΉ˜μ˜ μš”μ†Œκ°€ μ•„λ‹Œ μ½μ–΄μ˜¨ 것을 μ‚­μ œν•˜λŠ” 것에 μœ μ˜ν•˜μž.

5. Arrays

  Arrays ν΄λž˜μŠ€μ—λŠ” 배열을 λ‹€λ£¨λŠ” 데에 μœ μš©ν•œ λ©”μ„œλ“œκ°€ μ •μ˜λ˜μ–΄ μžˆλ‹€. 

λ°°μ—΄μ˜ 볡사 : copyOf(), copyOfRange()

λ°°μ—΄ μ±„μš°κΈ° : fill(), setAll()

λ°°μ—΄μ˜ μ •λ ¬κ³Ό 검색 : sort(), binarySearch()

λ°°μ—΄μ˜ 비ꡐ와 좜λ ₯ : equals(), toString(), deepToString(), deepEquals()

  * 닀차원 배열을 equals() 둜 λΉ„κ΅ν•˜λ©΄ λ°°μ—΄μ˜ μ£Όμ†Œλ₯Ό λΉ„κ΅ν•˜λ―€λ‘œ false κ°€ λ°˜ν™˜λ˜λ―€λ‘œ deepEquals() λ₯Ό μ‚¬μš©ν•  것.

배열을 List 둜 λ³€ν™˜ : asList(Object... a)

  * μ˜ˆμ‹œ)  List list = Arrays.asList(new Integer[]{1,2,3,4,5});  

               List list2 = Arrays.asList(1,2,3,4,5);

 * λ‹€λ§Œ asList 둜 얻은 List λŠ” 크기λ₯Ό λ³€κ²½ν•  수 μ—†λ‹€. 크기λ₯Ό λ³€κ²½ν•˜κ³ μž ν•œλ‹€λ©΄ μ•„λž˜μ™€ 같이 μ„ μ–Έν•  것.

              List list = new ArrayList(Arrays.asList(1,2,3,4,5));

parallelXXX(), spliterator(), stream()

:   parallel 둜 μ‹œμž‘ν•˜λŠ” λ©”μ„œλ“œλ“€μ€ 보닀 λΉ λ₯Έ κ²°κ³Όλ₯Ό μ–»κΈ° μœ„ν•΄ μ—¬λŸ¬ μ“°λ ˆλ“œκ°€ μž‘μ—…μ„ λ‚˜λˆ„μ–΄μ„œ μ²˜λ¦¬ν•œλ‹€. spliterator() 은 μ—¬λŸ¬ μ“°λ ˆλ“œκ°€ μ²˜λ¦¬ν•  수 μžˆλ„λ‘ ν•˜λ‚˜μ˜ μž‘μ—…μ„ μ—¬λŸ¬ μž‘μ—…μœΌλ‘œ λ‚˜λˆ„λŠ” Spliterator 을 λ°˜ν™˜ν•œλ‹€. stream 은 μ»¬λ ‰μ…˜μ„ 슀트림으둜 λ³€ν™˜ν•œλ‹€.

 

6. Comparator and Comparable

  Arrays.sort() λŠ” Character 클래슀의 Comparable 의 κ΅¬ν˜„μœΌλ‘œ λΆ€ν„° κ°€λŠ₯ν–ˆλ˜ 것이닀. Comparator 와 Comparable 은 interface 둜 collection 을 sorting ν•˜λŠ”λ°μ— ν•„μš”ν•œ λ©”μ„œλ“œλ₯Ό μ •μ˜ν•˜κ³  μžˆλŠ”λ°, Comparable 을 κ΅¬ν˜„ν•˜κ³  μžˆλŠ” ν΄λž˜μŠ€λ“€μ€ 같은 νƒ€μž…μ˜ μΈμŠ€ν„΄μŠ€λΌλ¦¬ μ„œλ‘œ 비ꡐ할 수 μžˆλŠ” ν΄λž˜μŠ€λ“€μ΄λ©° 기본적으둜 μ˜€λ¦„μ°¨μˆœμœΌλ‘œ μ •λ ¬λ˜λ„λ‘ κ΅¬ν˜„λ˜μ–΄ μžˆλ‹€. κ·Έλž˜μ„œ Comparable 을 κ΅¬ν˜„ν•œ ν΄λž˜μŠ€λŠ” sorting 이 κ°€λŠ₯ν•˜λ‹€λŠ” 것이닀. 

 

public interface Comparaotr{

int compare(Object o1, Object o2);

boolean equals(Object obj);

}

public interface Comparable{

public int compareTo(Object o);

}

 

  compare() 와 compareTo() λŠ” 같은 κΈ°λŠ₯을 λͺ©μ μœΌλ‘œ κ³ μ•ˆλœ 것이닀. 

 

public final class Integer extends Number implements Comparable {

...

public int compareTo(Object o){

return compareTo((Integer)o);

}

public int compareTo(Integer anotherInteger){

int thisVal = this.value;

int anotherVal = anotherInteger.value;

return (thisVal<anotherVal ? -1 : (thisVal == anotherVal ? 0 : 1));

   }

...

}

  Integer 클래슀λ₯Ό 보면 Comparable μΈν„°νŽ˜μ΄μŠ€μ˜ compareTo(Object to) 을 κ΅¬ν˜„ν•œ 것을 μ•Œ 수 μžˆλ‹€. Comparable μ„ κ΅¬ν˜„ν•œ ν΄λž˜μŠ€λ“€μ€ 기본적으둜 μ˜€λ¦„μ°¨μˆœ 정렬이 λ˜μ–΄μžˆμ§€λ§Œ, λ‹€λ₯Έ κΈ°μ€€μœΌλ‘œ μ •λ ¬ν•˜κ³ μž ν•  λ•Œμ—λŠ” Comparator 을 κ΅¬ν˜„ν•΄μ„œ μ •λ ¬ 기쀀을 λ§Œλ“€ 수 μžˆλ‹€.

import java.util.Arrays;
import java.util.Comparator;

public class source{
    public static void main(String[] args) {
        Integer[] arr = {1,2,3,4,5};

        Arrays.sort(arr, new Comparator<Integer>(){
            @Override
            public int compare(Integer i1, Integer i2){
                return i2-i1;
            }
        });

        print(arr);
    }
    public static void print(Integer[] arr){
        System.out.print("arr :");
        for(int ele : arr){
            System.out.print(ele + " ");
        }
    }
}

7. HashSet

    HashSet 에 μƒˆλ‘œμš΄ μš”μ†Œλ₯Ό μΆ”κ°€ν•  λ•Œμ—λŠ” add λ‚˜ addAll 을 μ‚¬μš©ν•˜λŠ”λ°, 이미 μ €μž₯된 μš”μ†Œμ™€ μ€‘λ³΅λœ μš”μ†Œλ₯Ό μΆ”κ°€ν•˜λ €κ³  ν•œλ‹€λ©΄ false λ₯Ό λ°˜ν™˜ν•œλ‹€. HashSet 은 μ €μž₯μˆœμ„œλ₯Ό μœ μ§€ν•˜μ§€ μ•ŠμœΌλ―€λ‘œ, λ§Œμ•½ μ €μž₯μˆœμ„œλ₯Ό μœ μ§€ν•˜κ³ μž ν•œλ‹€λ©΄ LinkedHashSet 을 μ‚¬μš©ν•˜μ—¬μ•Ό ν•œλ‹€. 

import java.util.HashSet;
import java.util.Set;
class source{
    public static void main(String[] args) {
        Object[] arr = {"1", 1, "2", "2", "3", "3", "4", "4", "4"};
        Set set = new HashSet();

        for(int i = 0 ; i < arr.length; i++){
            set.add(arr[i]);
        }
        System.out.println(set);
    }
}

 

λ§Œμ•½ 쀑볡을 μ œκ±°ν•¨κ³Ό λ™μ‹œμ— μ €μž₯ μˆœμ„œλ₯Ό μœ μ§€ν•˜κ³ μž ν•œλ‹€λ©΄ LinkedHashSet 을 μ‚¬μš©ν•˜λ©΄ λœλ‹€.

import java.util.*;

class source{
    public static void main(String[] args) {
        Set set = new HashSet();
        for(int i = 0 ; set.size()<6; i++){
            int num = (int)(Math.random()*45)+1;
            set.add(num);
        }
        List list = new LinkedList(set); // LinkedList(Collection c)
        Collections.sort(list);
        System.out.println(list);
    }
}

μ•„λž˜λŠ” 1~50 의 숫자 쀑, 쀑볡없이 25개λ₯Ό κ³¨λΌμ„œ 5 by 5 matrix 둜 λ§Œλ“€μ–΄ 좜λ ₯ν•˜λŠ” μ˜ˆμ œμ΄λ‹€. 

import java.util.*;

class source {
    public static void main(String[] args) {
        Set set = new LinkedHashSet();
        int[][] board = new int[5][5];

        for (int i = 0; set.size() < 25; i++) {
            set.add((int) (Math.random() * 50) + 1 + "");
        }
        Iterator it = set.iterator();

        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[i].length; j++) {
                board[i][j] = Integer.parseInt((String) it.next());
                System.out.print((board[i][j] < 10 ? "  " : " ") + board[i][j]);
            }
            System.out.println();
        }
    }
}

μ•„λž˜μ˜ Person 클래슀λ₯Ό μš”μ†Œλ‘œ κ°€μ§€λŠ” HashSet 을 μ‚΄νŽ΄λ³΄μž.

import java.util.HashSet;

class source {
    public static void main(String[] args) {
        HashSet set = new HashSet();

        set.add("abc");
        set.add("abc");
        set.add(new Person("David", 10));
        set.add(new Person("David", 10));

        System.out.println(set);
    }
}
class Person{
    String name;
    int age;

    Person(String name, int age){
        this.name = name;
        this.age = age;
    }
    public String toString(){
        return name +":"+ age;
    }
}

μ‹€ν–‰κ²°κ³Όλ₯Ό 보면 μ˜ˆμƒκ³ΌλŠ” 달리 David:10 이 μ€‘λ³΅λ˜μ–΄ μ €μž₯된 것을 λ³Ό 수 μžˆλ‹€. HashSet λ©”μ„œλ“œμ˜ add λ©”μ„œλ“œλŠ” μƒˆλ‘œμš΄ μš”μ†Œλ₯Ό μΆ”κ°€ν•  λ•Œ, κΈ°μ‘΄ μ €μž₯된 μš”μ†Œμ™€ 같은지 νŒλ³„ν•˜κΈ° μœ„ν•΄ μΆ”κ°€ν•˜λ €λŠ” μš”μ†Œμ˜ equals() λ©”μ†Œλ“œμ™€ hashCode() λ₯Ό ν˜ΈμΆœν•΄μ„œ 이에 λŒ€ν•œ μ˜€λ²„λΌμ΄λ”©μ„ ν•΄μ£Όμ–΄μ•Ό μ˜λ„λŒ€λ‘œ λ™μž‘ν•œλ‹€.

import java.util.HashSet;

class source {
    public static void main(String[] args) {
        HashSet set = new HashSet();

        set.add("abc");
        set.add("abc");
        set.add(new Person("David", 10));
        set.add(new Person("David", 10));

        System.out.println(set);
    }
}
class Person{
    String name;
    int age;

    Person(String name, int age){
        this.name = name;
        this.age = age;
    }
    public String toString(){
        return name +":"+ age;
    }
    public boolean equals(Object obj){
        if(obj instanceof Person){
            Person tmp = (Person) obj;
            return name.equals(tmp.name) && age==tmp.age;
        }
        return false;
    }
    public int hashCode(){
        return (name+age).hashCode();
    }
}

  μ˜€λ²„λΌμ΄λ”©μ„ 톡해 μž‘μ„±ν•œ hashcode() λ©”μ„œλ“œλŠ” μ•„λž˜μ˜ 3 가지 사항을 λ§Œμ‘±ν•΄μ•Όν•œλ‹€.

 

1. 싀행쀑인 application λ‚΄ λ™μΌν•œ 객체에 λŒ€ν•΄ hashCode() λ₯Ό μ—¬λŸ¬ 번 호좜 ν•˜λ”λΌλ„ λ™μΌν•œ int 값을 λ°˜ν™˜ν•΄μ•Ό ν•œλ‹€. ν•˜μ§€λ§Œ, μ‹€ν–‰μ‹œλ§ˆλ‹€ λ™μΌν•œ int 값을 λ°˜ν™˜ν•  ν•„μš”λŠ” μ—†λ‹€. (단, equals λ©”μ„œλ“œμ˜ κ΅¬ν˜„μ— μ‚¬μš©ν•œ λ©€λ²„λ³€μˆ˜μ˜ 값이 λ°”λ€Œμ§€ μ•Šμ•˜λ‹€κ³  가정함.)

 

2. equals λ©”μ„œλ“œλ₯Ό μ΄μš©ν•œ 비ꡐ 연산에 μ˜ν•΄ true λ₯Ό 얻은 두 객체에 λŒ€ν•˜μ—¬ 각각 hashCode() λ₯Ό ν˜ΈμΆœν•΄μ„œ 얻은 κ²°κ³ΌλŠ” λ°˜λ“œμ‹œ κ°™μ•„μ•Ό ν•œλ‹€.

 

3. equals λ©”μ„œλ“œλ₯Ό ν˜ΈμΆœν–ˆμ„ λ•Œ false λ₯Ό λ°˜ν™˜ν•˜λŠ” 두 κ°μ²΄λŠ” hashcode() ν˜ΈμΆœμ— λŒ€ν•΄ 같은 int 값을 λ°˜ν™˜ν•˜λŠ” κ²½μš°κ°€ λ°œμƒν•΄λ„ λ˜μ§€λ§Œ, hashing 을 μ‚¬μš©ν•˜λŠ” collection 의 μ„±λŠ₯을 ν–₯μƒμ‹œν‚€κΈ° μœ„ν•΄μ„  λ°˜λ“œμ‹œ λ‹€λ₯Έ int 값을 λ°˜ν™˜ν•˜λ„λ‘ ν•˜λŠ” 것이 μ’‹λ‹€.

8. TreeSet

   TreeSet 은 λ°”μ΄λ„ˆλ¦¬νŠΈλ¦¬ ν˜•νƒœλ‘œ 데이터λ₯Ό μ €μž₯ν•˜λŠ” Collection class 이닀. λ°”μ΄λ„ˆλ¦¬ νŠΈλ¦¬λŠ” sorting, searching, range searching 에 높은 μ„±λŠ₯을 보이며, TreeSet 은 λ°”μ΄λ„ˆλ¦¬ 트리λ₯Ό κ°œμ„ μ‹œν‚¨ Red - Black Tree ꡬ쑰둜 λ˜μ–΄μžˆλ‹€. Set μΈν„°νŽ˜μ΄μŠ€λ₯Ό κ΅¬ν˜„ν•œ κ²ƒμ΄λ―€λ‘œ 쀑볡을 ν—ˆμš©ν•˜μ§€ μ•ŠμœΌλ©°, μ €μž₯ μˆœμ„œλ„ μœ μ§€ν•˜μ§€ μ•ŠλŠ”λ‹€. 

import java.util.TreeSet;

class source {
    public static void main(String[] args) {
        TreeSet set = new TreeSet();
        int[] score = {80, 95, 50, 35, 45, 65, 10, 100};

        for(int i=0; i<score.length; i++)
            set.add(score[i]);

        System.out.println("less than 50 : " + set.headSet(50));
        System.out.println("bigger than 50 : " + set.tailSet(50));
    }
}

headSet λ©”μ„œλ“œμ™€ tailSet λ©”μ„œλ“œλ₯Ό μ΄μš©ν•˜λ©΄ κΈ°μ€€ 값보닀 큰/μž‘μ€ 객체듀을 얻을 수 μžˆλ‹€.

9. HashMap  

 HashMap 은 Map 을 κ΅¬ν˜„ν•œ κ²ƒμœΌλ‘œ key-value ν˜•νƒœμ˜ 값을 λ°μ΄ν„°λ‘œ μ €μž₯ν•œλ‹€. λ˜ν•œ hashing 을 μ‚¬μš©ν•˜λ―€λ‘œ 검색에 μžˆμ–΄μ„œ λ›°μ–΄λ‚œ μ„±λŠ₯을 보인닀. 

 

public class HashMap extends AbstractMap implements Map, Cloneable, Serializable{

trainsient Entry[] table;

...

static class Entry implements Map.Entry{

final Object key;

Object value;

...

     }

}

 

 μœ„λŠ” μ‹€μ œ μ†ŒμŠ€μ½”λ“œμ˜ 일뢀인데,  Entry λΌλŠ” inner class λ₯Ό μ •μ˜ν•˜κ³  Entry νƒ€μž…μ˜ 배열을 μ„ μ–Έν•˜κ³  μžˆλ‹€. key - value ν˜•νƒœμ˜ 데이터이기 λ•Œλ¬Έμ— ν•˜λ‚˜μ˜ 클래슀둜 μ •μ˜ν•΄μ„œ λ‹€λ£¨λŠ” 것이 data integrity μΈ‘λ©΄μ—μ„œ λ°”λžŒμ§ν•˜κΈ° λ•Œλ¬Έμ΄λ‹€.

import java.util.HashMap;
import java.util.Scanner;

class source {
    public static void main(String[] args) {
        HashMap map = new HashMap();
        map.put("myId", "1234");
        map.put("asdf", "1111");
        map.put("asdf", "1234");

        Scanner s = new Scanner(System.in);

        while (true) {
            System.out.println("Enter Id, password");
            System.out.print("id :");
            String id = s.nextLine().trim();

            System.out.print("password :");
            String password = s.nextLine().trim();
            System.out.println();

            if (!map.containsKey(id)) {
                System.out.println("there is no id, please enter again.");
                continue;
            }
            if (!(map.get(id)).equals(password)) {
                System.out.println("Passwords do not match, please try again.");
            } else {
                System.out.println("success!!");
                break;
            }
        }
    }
}

맨 μ²˜μŒμ— asdf λΌλŠ” key λ₯Ό μ€‘λ³΅ν•΄μ„œ λ„£μ—ˆκΈ° λ•Œλ¬Έμ—, λ§ˆμ§€λ§‰μ— put ν•œ key-value 만 μ‚΄μ•„λ‚¨λŠ”λ‹€.

import java.util.*;

class source {
    public static void main(String[] args) {
        HashMap map = new HashMap();
        map.put("Kim", 100);
        map.put("Lee", 100);
        map.put("Kang", 100);
        map.put("Ahn", 100);

        Set set = map.entrySet();
        Iterator it = set.iterator();

        while(it.hasNext()){
            Map.Entry e = (Map.Entry)it.next();
            System.out.println("name : " + e.getKey() + "score : " + e.getValue());
        }

        set = map.keySet();
        System.out.println("participant list : " + set);

        Collection values = map.values();
        it = values.iterator();

        int total = 0;
        while(it.hasNext()){
            Integer i = (Integer)it.next();
            total += i.intValue();
        }

        System.out.println("total : " + total);
        System.out.println("average : " + (float)total/set.size());
        System.out.println("max : " + Collections.max(values));
        System.out.println("min : " + Collections.min(values));
    }
}

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

class source {
    static HashMap phoneBook = new HashMap();
    public static void main(String[] args) {
       addPhoneNo("Friend", "Lee", "010-1111-1111");
       addPhoneNo("Friend", "Ki", "010-1121-1141");
       addPhoneNo("Friend", "Kim", "010-3111-1111");
       addPhoneNo("Job", "Ted", "010-5111-1111");
       addPhoneNo("Job", "James", "010-6111-1111");
       addPhoneNo("Job", "Travis", "010-7111-1111");
       addPhoneNo("Job", "Gael", "010-8111-1111");
       addPhoneNo("Food", "KFC", "010-9111-1111");

       printList();
    }
    static void addPhoneNo(String groupName, String name, String tel){
        addGroup(groupName);
        HashMap group = (HashMap)phoneBook.get(groupName);
        group.put(tel, name);
    }
    static void addGroup(String groupName){
        if(!phoneBook.containsKey(groupName))
            phoneBook.put(groupName, new HashMap());
    }
    static void addPhoneNo(String name, String tel){
        addPhoneNo("etc", name, tel);
    }
    static void printList(){
        Set set = phoneBook.entrySet();
        Iterator it = set.iterator();

        while(it.hasNext()){
            Map.Entry e = (Map.Entry)it.next();

            Set subSet = ((HashMap)e.getValue()).entrySet();
            Iterator subIt = subSet.iterator();

            System.out.println(" * " + e.getKey()+"[" + subSet.size() + "]");

            while(subIt.hasNext()){
                Map.Entry subE = (Map.Entry)subIt.next();
                String telNo = (String)subE.getKey();
                String name = (String)subE.getValue();
                System.out.println(name + " " + telNo);
            }
            System.out.println();
        }
    }
}

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

class source {
    static HashMap phoneBook = new HashMap();
    public static void main(String[] args) {
        String[] data = {"A", "B", "C", "D", "E", "F", "G", "A", "A", "B", "C", "G", "A", "A", "A"};

        HashMap map = new HashMap();

        for(int i=0; i<data.length; i++){
            if(map.containsKey(data[i])){
                Integer value = (Integer) map.get(data[i]);
                map.put(data[i], value.intValue() +1);
            } else {
                map.put(data[i], 1);
            }
        }
        Iterator it = map.entrySet().iterator();

        while(it.hasNext()){
            Map.Entry entry = (Map.Entry)it.next();
            int value = ((Integer)entry.getValue()).intValue();
            System.out.println(entry.getKey() + " : " + printBar('#', value) + " " + value);
        }
    }

    public static String printBar(char ch, int value){
        char[] bar = new char[value];

        for(int i=0; i<bar.length; i++)
            bar[i] = ch;

        return new String(bar);
    }
}

  String 배열인 data λ₯Ό μˆœνšŒν•˜λ©°, ν˜„μž¬ HashMap 에 data[i] 와 μ€‘λ³΅λ˜λŠ” key κ°€ μ—†μœΌλ©΄ map.put(data[i], new Integer(1)); 을 μˆ˜ν–‰ν•˜κ³  λ§Œμ•½ HashMap 에 data[i] 와 μ€‘λ³΅λ˜λŠ” key κ°€ μ‘΄μž¬ν•˜λ©΄ value λ₯Ό μ–»μ–΄μ˜€κ³ , value 에 1 을 λ”ν•œ 값을 value 둜 ν•΄μ„œ λ‹€μ‹œ put ν•΄μ€€λ‹€. 그러면 HashMap μ—λŠ” data λ°°μ—΄μ˜ μ›μ†Œμ˜ λΉˆλ„κ°€ μ €μž₯되며 이λ₯Ό iterator 을 μ΄μš©ν•˜μ—¬ μˆœνšŒν•˜λŠ”λ°, printBar ν•¨μˆ˜λ₯Ό μ΄μš©ν•΄μ„œ κ·Έλž˜ν”„λ₯Ό κ·Έλ €μ£ΌλŠ” μ˜ˆμ œμ΄λ‹€. 

 

[ Hash Function ]

  Hashing 을 κ΅¬ν˜„ν•œ μ»¬λ ‰μ…˜ ν΄λž˜μŠ€λŠ” HashSet, HashMap, Hashtable 등이 있으며 Hashtable 은 collections framework κ°€ λ„μž…λ˜λ©° HashMap 으둜 λŒ€μ²΄λ˜μ—ˆμœΌλ‚˜, 이전에 μž‘μ„±λœ μ½”λ“œμ™€μ˜ ν˜Έν™˜μ„ μœ„ν•΄ λ‚¨μ•„μžˆλŠ” 것이닀. 

10. TreeMap

   λ°”μ΄λ„ˆλ¦¬μ„œμΉ˜νŠΈλ¦¬ ν˜•νƒœλ‘œ key-value 의 pair 데이터λ₯Ό μ €μž₯ν•˜λ―€λ‘œ 검색과 정렬에 μ ν•©ν•œ ν΄λž˜μŠ€μ΄λ‹€. λ‹€λ§Œ 검색 μ„±λŠ₯에 κ΄€ν•΄μ„œλŠ” HashMap 이 TreeMap 보닀 λŒ€λΆ€λΆ„ μš°μˆ˜ν•˜λ―€λ‘œ HashMap 을 μ‚¬μš©ν•˜λŠ” 것이 μ’‹λ‹€. range search λ‚˜ sorting 의 κ²½μš°μ—λŠ” TreeMap 이 μš°μˆ˜ν•˜λ‹€.

 

11. Properties

   Hashtable 을 상속받아 κ΅¬ν˜„ν•œ κ²ƒμœΌλ‘œ key - value 값을 String, String ν˜•νƒœλ‘œ μ €μž₯ν•œλ‹€. μ–΄ν”Œλ¦¬μΌ€μ΄μ…˜μ˜ ν™˜κ²½μ„€μ •κ³Ό κ΄€λ ¨λœ property λ₯Ό μ €μž₯ν•˜λŠ”λ°μ— 주둜 μ‚¬μš©λ˜λ©° 데이터λ₯Ό νŒŒμΌλ‘œλΆ€ν„° 읽고 μ“°λŠ” νŽΈλ¦¬ν•œ κΈ°λŠ₯을 μ œκ³΅ν•œλ‹€. 

import java.util.Enumeration;
import java.util.Properties;

class source{
    public static void main(String[] args) {
        Properties prop = new Properties();

        prop.setProperty("timeout", "30");
        prop.setProperty("language", "kr");
        prop.setProperty("size", "10");
        prop.setProperty("capacity", "10");

        Enumeration e = prop.propertyNames();

        while(e.hasMoreElements()){
            String element = (String)e.nextElement();
            System.out.println(element + "=" + prop.getProperty(element));
        }

        System.out.println();
        prop.setProperty("size", "20");
        System.out.println("size=" + prop.getProperty("size"));
        System.out.println("capacity=" + prop.getProperty("capacity", "20"));
        System.out.println("load-factor=" + prop.getProperty("load-factor", "0.75"));

        System.out.println(prop);
        prop.list(System.out);
    }
}

12. Collections

   Collections ν΄λž˜μŠ€λŠ” μ»¬λ ‰μ…˜κ³Ό κ΄€λ ¨λœ fill, copy, sort, binarySearch λ“±μ˜ λ©”μ„œλ“œλ₯Ό μ œκ³΅ν•œλ‹€. multi-thread ν”„λ‘œκ·Έλž˜λ°μ—μ„œ ν•˜λ‚˜μ˜ 객체λ₯Ό μ—¬λŸ¬ thread κ°€ λ™μ‹œμ— μ ‘κ·Όν•  수 μžˆμ–΄μ„œ data inconsistency λ₯Ό μœ„ν•΄μ„œλŠ” κ³΅μœ λ˜λŠ” 객체에 synchronization 을 ν•΄μ£Όμ–΄μ•Ό ν•œλ‹€. Vector, Hashtable 은 자체적으둜 동기화 μ²˜λ¦¬κ°€ λ˜μ–΄μžˆμ§€λ§Œ multi-threading 을 μ‚¬μš©ν•˜μ§€ μ•ŠλŠ” κ²½μš°μ—λŠ” μ„±λŠ₯을 μ €ν•˜μ‹œν‚€λŠ” μš”μΈμ΄ λ˜λ―€λ‘œ, JAVA 에 μƒˆλ‘œ μΆ”κ°€λœ ArrayList 와 HashMap 등은 동기화 μ²˜λ¦¬κ°€ λ˜μ–΄μžˆμ§€ μ•Šμ€λ°, μ΄λŠ” ν•„μš”ν•œ κ²½μš°μ—λ§Œ java.util.Collections μ—μ„œ Synchronization λ©”μ„œλ“œλ₯Ό μ΄μš©ν•΄μ„œ μ²˜λ¦¬ν•΄μ£Όλ„λ‘ ν•˜κΈ° μœ„ν•¨μ΄λ‹€. 

  λ˜ν•œ μ»¬λ ‰μ…˜μ˜ 데이터λ₯Ό λ³΄ν˜Έν•˜κΈ° μœ„ν•΄ read - only 둜 λ§Œλ“€μ–΄μ•Ό ν•  κ²½μš°κ°€ λ°œμƒν•˜λŠ”λ° μ΄λŠ” Collection 의 unmodifiable... λ©”μ„œλ“œλ₯Ό μ‚¬μš©ν•˜λ©΄ λœλ‹€. 그리고 였직 ν•˜λ‚˜μ˜ 객체만 μ €μž₯ν•˜λŠ” μ»¬λ ‰μ…˜(싱글톀 μ»¬λ ‰μ…˜)을 λ§Œλ“€κ³ μž ν•  λ•Œμ—λŠ” singleton... λ©”μ„œλ“œλ₯Ό μ‚¬μš©ν•˜λ©΄ λœλ‹€. μ»¬λ ‰μ…˜μ— ν•œ μ’…λ₯˜μ˜ 객체만 μ €μž₯ν•˜λ„λ‘ ν•˜λŠ” κ²½μš°μ—λŠ” checked ... λ©”μ†Œλ“œλ₯Ό μ‚¬μš©ν•˜λ©΄ λœλ‹€. 


References

http://www.yes24.com/Product/Goods/24259565

 

Java의 정석 - YES24

졜근 7λ…„λ™μ•ˆ μžλ°” λΆ„μ•Όμ˜ 베슀트 μ…€λŸ¬ 1μœ„λ₯Ό μ§€μΌœμ˜¨ `μžλ°”μ˜ 정석`의 μ΅œμ‹ νŒ. μ €μžκ°€ μΉ΄νŽ˜μ—μ„œ 12λ…„κ°„ 직접 λ…μžλ“€μ—κ²Œ 닡변을 ν•΄μ˜€λ©΄μ„œ μ΄ˆλ³΄μžκ°€ μ–΄λ €μ›Œν•˜λŠ” 뢀뢄을 잘 νŒŒμ•…ν•˜κ³  μ“΄ μ±…. 뿐만 μ•„

www.yes24.com

 

 

728x90
λ°˜μ‘ν˜•
LIST
Comments