티스토리 뷰

728x90

서문



자바의 정석 기초편 챕터 11편을 기재합니다.
목적은 공부한 내용을 기록하는 것에 있기 때문에 완전한 문장이 아닐 수도 있습니다.
또한 모든 내용을 적은 것은 아닙니다.









자바의 정석 ( ch.11 )



컬렉션 프레임워크(collections framework)


  • 컬렉션(collections)
    • 여러 객체(데이터)를 모아 둔 것

  • 프레임워크(framework)
    • 표준화, 정형화된 체계적인 프로그래밍 방식
      • 유지보수
      • 생산성

  • 컬렉션 프레임워크
  • 여러 객체를 다루기 위한 표준화된 프로그래밍 방식
  • 컬렉션을 쉽고 편리하게 다룰 수 있는 다양한 클래스를 제공
  • java.util패키지에 포함, JDK1.2부터 제공

  • 컬렉션 클래스

    • List + Set의 공통부분 = Collection 인터페이스
    • 다수의 데이터를 저장할 수 있는 클래스(Vector, ArrayList,HashSet 등등)

    • List
      • 순서가 있는 데이터 집합, 데이터 중복이 허용됨
      • 예) 대기자 명단
      • ArrayList, LinkedList, Stack, Vector 등

    • Set
      • 순서를 유지하지 않는 데이터의 집합, 데이터 중복을 허용 하지 않음 ( 우리가 아는 집합 )
      • 예) 양의 정수집합, 소수의 집합
      • HashSet, TreeSet 등

    • Map
      • 키(key)와 값(value)의 쌍(pair)으로 이루어진 데이터 집합, 순서가 유지되지 않으며 키는 중복을 허용하지 않음, 값은 중복 허용
      • 예) 우편번호, 지역번호(전화번호)
      • HashMap, TreeMap, HashTable, Properties 등

  • 추가, 삭제, 검색 등 기능이 대표적
메서드 설명
boolean add(Object o )
boolean addAll(Collection c)
지정된 객체(o) 또는 Collection(c)의 객체들을 Collection에 추가
void clear() Collection의 모든 객체를 삭제
boolean contains(Object o )
boolean contains(Collection c)
지정된 객체(o) 또는 Collection(c)의 객체들이 Collection에 포함되어 있는지 확인
boolean equals(Object o ) 동일한 Collection인지 비교
int hashCode() Collection의 해시코드를 반환
boolean isEmpty() Collection이 비어 있는지 확인
iterator iterator() Collection의 iterator를 얻어서 반환
boolean remove(Object o) 지정된 객체를 삭제
boolean removeAll(Collection c) 지정된 Collection에 포함된 객체를 삭제
boolean retainAll(Collection c) 지정된 Collection에 포함된 객체만을 남기고 다른 객체들은 Collection에서 삭제, 이 작업으로 인해 Collection의 변화가 있으면 true, 없으면 false를 반환
int size() Collection의 저장된 객체의 수를 반환
Object[] toArray() Collection에 저장된 객체를 객체배열(Object[])로 반환
Object[] toArray(Object[] a) 지정된 배열에 Collection의 객체를 저장해서 반환


List인터페이스 (순서 o, 중복 o)

  • Vector, ArrayList, LinkedList
  • 추가, 검색, 삭제, 정렬
메서드 설명
void add(int index, Object o)
boolean addAll(int index, Collection c)
지정된 위치(index)에 객체 또는 컬렉션에 포함된 객체를 추가
Object get(int index) 지정된 위치(index)에 있는 객체를 반환
int indexOf(Object o) 지정된 객체의 위치(index)를 반환(List의 첫 번째 요소부터 순방향으로 검색)
int lastIndexOf(Object o) 지정된 객체의 위치를 반환(List의 마지막 요소부터 역방향으로 검색)
ListIterator listIterator()
ListIterator listIterator(int index)
List의 객체에 접근할 수 있는 Iterator를 반환
Object remove(int index) 지정된 위치(index)에 있는 객체를 삭제하고, 삭제된 객체를 반환
Object set(int index, Object o) 지정된 위치에 객체를 저장
void sort(Comparator c) 지정된 비교자(Comparator)로 List를 정렬함
List subList(int fromIndex, int toIndex) 지정된 범위(fromIndex ~ toIndex)에 있는 객체를 반환


Set 인터페이스 (순서 x, 중복 x)

  • hashSet, TreeSet, SortedSet
  • Collection 인터페이스의 메서드와 동일 + 집합과 관련된 메서드(변화가 있으면 true, 없으면 false)
메서드 설명
boolean addAll(Collection c) 지정된 Collection(c)의 객체들을 Collection에 추가(합집합)
boolean containAll(Collection c) 지정된 Collection(c)의 객체들이 Collection에 포함되어 있는지 확인(부분집합)
boolean removeAll(Collection c) 지정된 Collection(c)에 포함된 객체들을 삭제(차집합)
boolean retainAll(Collection c) 지정된 Collection(c)에 포함된 객체들만 남기고 나머지는 Collection에서 삭제 (교집합)


Map 인터페이스 (순서 x, 중복 - 키(x), 값(o))

  • HashTable, HashMap(LinkedHashMap의 부모), SortedMap(TreeMap의 부모)
메서드 설명
void clear() Map의 모든 객체를 삭제
boolean containsKey(Object key) 지정된 key객체와 일치하는 Map의 key객체가 있는지 확인
boolean containsValue(Object value) 지정된 value객체와 일치하는 Map의 value객체가 있는지 확인
Set entrySet() Map에 저장되어 있는 key-value쌍을 Map,Entry(key-value)타입의 객체로 저장한 Set으로 반환
boolean equals(Object o) 동일한 Map인지 비교
Object get(Object key) 지정한 key객체에 대응하는 value객체를 찾아서 반환
int hashCode() Map의 해시코드를 반환
boolean inEmpty() Map이 비어 있는지 확인
Set KeySet() Map에 저장된 모든 key객체를 반환
Object put(Object key, Object value) Map에 value객체를 key객체에 연결(mapping)하여 저장
void putAll(Object key) 지정한 key객체와 일치하는 key-value 쌍을 추가
Object remove(Object key) 지정한 key객체와 일치하는 key-value쌍을 삭제
int size() Map에 저장된 key-value쌍의 수를 반환
Collection values() Map에 저장된 모든 value객체를 반환



ArrayList

  • ArrayList는 기존의 Vector를 개선한 것으로 구현원리와 기능적으로 동일, ArrayList와 달리 Vector는 자체적으로 동기적처리가 되어 있음
  • List인터페이스를 구현하므로, 저장순서 o, 중복 o
  • 데이터의 저장공간으로 배열을 사용
  • 모든 객체를 담을 수 있음
public class Vector extends AbstractList implements List, RandomAccess, Cloneable, java.io.Serializable{
  ...
  protected Object[] elementData; // 모든 객체를 담기 위한 공간
}


생성자 및 메서드

구조 설명
ArrayList()
ArrayList(Collection c)
ArrayList(int initialCapacity)
ArrayList의 생성자들, 기본생성자와 컬렉션, 배열의 길이를 넣어서 만들 수 있음
boolean add(Object obj) 객체를 추가
void add(int index, Object element) 지정한 위치에 객체를 추가
boolean addAll(Collection c) 컬렉션이 가진 요소들을 모두 추가
boolean addAll(int index, Collection c) 지정한 위치에 객체의 요소들을 추가
boolean remove(Object obj) 객체를 삭제
Object remove(int index) 지정한 위치의 객체를 삭제하고 반환
boolean removeAll(Collection c) ArrayList에 있는 컬렉션의 요소들을 모두 삭제
void clear() ArrayList에 있는 모든 객체를 삭제
int indexOf(Object obj) 지정한 객체가 어디에 위치하는지 확인
int lastIndexOf(Object obj) 지정한 객체가 마지막부터 어디에 존재하는지 확인
boolean contains(Object obj) 해당 객체가 ArrayList에 존재하는지 확인
Object get(int idex) 지정한 위치에 있는 객체를 반환
Object set(int index, Object obj) 지정한 위치에 존재하는 객체를 지정한 객체로 수정
List subList(int fromIndex, int toIndex) 지정한 범위의 요소들을 리스트로 반환
Object[] toArray() ArrayList가 가지고 있는 객체를 배열로 반환
Object[] toArray(Object[] obj) 지정한 타입의 오브젝트로 반환
boolean isEmpty() ArrayList가 비어있는지 확인
void trimToSize() ArrayList의 빈공간을 제거
int size() ArrayList에 저장된 객체의 수를 반환
class Ex{
  public static void main(String[] args){
    ArrayList arr = new ArrayList(10);
    // 객체만 저장 가능, 기본형으로 매개변수를 넣으면 자동으로 래퍼형으로 바꿔줌

    arr.add(5); // arr.add(new Integer(5));
    arr.add(4); // arr.add(new Integer(4));
    arr.add(3); // arr.add(new Integer(3));
    arr.add(2); // arr.add(new Integer(2));
    arr.add(1); // arr.add(new Integer(1));
    arr.add(0); // arr.add(new Integer(0));

    ArrayList arr2 = new ArrayList(arr.subList(0,3));

    System.out.println(arr);
    System.out.println(arr2);

    arr.set(0,50);
    System.out.println(arr);

    arr.set(0,"1");

    System.out.println(arr.indexOf("1"));
    System.out.println(arr.indexOf(1));
    System.out.println(arr);


    arr.remove("1");
    System.out.println(arr);

    arr.remove(1);
    System.out.println(arr);

    arr.remove(new Integer(1));
    System.out.println(arr);
  }
}


> [5, 4, 3, 2, 1, 0]
> [5, 4, 3]
> [50, 4, 3, 2, 1, 0]
> [1, 4, 3, 2, 1, 0] // 이때 index(0)은 "1" 문자열이다.
> 0
> 4
> [4, 3, 2, 1, 0] // arr.remove("1")을 하면 index(0)에 해당하는 값이 지워짐
> [4, 2, 1, 0] // arr.remove(1)을 하면 index(1)에 해당하는 값이 지워짐
> [4, 2, 0] // arr.remove(new Integer(1))을 하면 1이라는 값이 지워짐, java9부터 new Integer()로 사용하지 않으며 Integer.valueOf(1)이런 식으로 사용


ArrayList에 저장된 객체의 삭제 과정

  • 삭제할 데이터 아래의 데이터를 한 칸씩 위로 복사해서 삭제할 데이터를 덮음
  • 데이터가 모두 한 칸씩 이동했으므로 마지막 데이터를 null로 변경
  • 데이터가 삭제되어 데이터의 개수가 줄었으니 size의 값을 줄임
  • 마지막 데이터를 삭제하는 경우 1번의 과정을 안함
    • ArrayList를 모두 삭제하고 싶을 때 객체에 접근하여 삭제하는 경우, 뒤부터 삭제해주는 것이 성능이 빠름(복사가 발생하지 않음)
1. 만약에 ArrayList의 객체를 다 지우고 싶을 때, 앞부터 지우는 경우

ArrayList arr = new ArrayList(5);
arr.add(1);
arr.add(2);
arr.add(3);
arr.add(4);
arr.add(5);
for (int i = 0; i<arr.size(); i++){ // 삭제할 때마다 복사가 발생하므로 ArrayList가 삭제 후 하나 씩 줄어서 기대와 다른 결과 발생
  arr.remove(i);
}

System.out.println(arr)


> [2, 4]

-------------------------------------------

2. 뒤부터 지우는 경우

ArrayList arr = new ArrayList(5);
arr.add(1);
arr.add(2);
arr.add(3);
arr.add(4);
arr.add(5);
for (int i = arr.size()-1; i>=0; i--){ // 뒤부터 삭제할 경우 복사가 발생하지 않아서 속도면에서도 더 빠르면서 원하는 결과를 얻을 수 있음
  arr.remove(i);
}

System.out.println(arr)


> []


LinkedList



배열의 장단점


  • 장점

    • 배열의 구조는 간단
    • 데이터를 읽는 속도(접근시간, access time)이 짧음(연속적인 데이터이기 떄문에, 객체주소에 접근하기 쉬움)

  • 단점

    • 크기를 변경할 수 없음(실행 중에)
      • 크기를 변경해야 하는 경우, 새로운 배열을 생성 후 복사해야 함
        1. 더 큰 배열 생성
        1. 복사
        1. 참조변수 변경(주소변경)

    • 비순차적인 데이터의 추가, 삭제에 시간이 오래 걸림
      • 데이터를 추가 삭제할 때, 다른 데이터도 다 옮겨야 함
      • 그러나 순차적인 데이터의 추가나 삭제는 빠름(극단의 데이터들)


  • LinkedList는 배열의 단점을 보완
    • 배열과 달리 불연속적인 데이터를 연결(Link)
    • 불연속적인 데이터의 추가와 삭제에 용이

  • 데이터의 삭제
    • 단 한번의 참조변경만으로 가능
    • 참조변수가 연결되지 않는 데이터는 gc(가비지 컬렉터)가 자동으로 삭제처리





  • 데이터의 박스 하나 하나를 node라고 함
class Node{
  Node next; // 참조
  Object obj; // 데이터
}

  • 데이터의 추가
  • 한번의 Node객체생성과 두번의 참조변경만으로 가능





  • LinkedList의 단점
    • 데이터 접근성이 나쁨(첫 번째 요소는 두 번째 요소만을 앎, 불연속적)
      • 이를 해결하기 위해 더블리 링크드 리스트(doubly linked list)방법을 사용(이중연결리스트)


class Node{
  Node next; // 다음참조
  Node previous; // 이전참조
  Object obj; // 데이터
}


  • 더블리 써큘러 링크드 리스트(doubly circular linked list) : 이중 원형 연결리스트
    • 마지막 원소들을 각 처음과 마지막으로 연결시켜서 하나의 원형을 이루는 연결리스트





  • ArrayList vs LinkedList 성능 비교




  • 순차적 추가

    • ArrayList > LinkedList
  • 순차적 삭제

    • ArrayList > LinkedList
  • 중간에 추가

    • LinkedList >> ArrayList
  • 중간에서 삭제

    • LinkedList >> ArrayList
  • 접근시간

    • ArrayList >> LinkedList
    • ArrayList는 첫 번째 요소에서 몇 번째 요소인지만 안다면 한번의 연산으로 접근이 가능하므로 (1)
    • 배열의 주소 + n * 데이터 타입의 크기


  • 정리
컬렉션 읽기(접근시간) 추가/삭제 비고
ArrayList 빠르다 느리다 순차적 추가삭제는 더 빠름, 비효율적인 메모리 사용
LinkedList 느리다 빠르다 데이터가 많을수록 접근성이 떨어짐



스택과 큐(Stack & Queue)



스택

  • LIFO구조, 마지막에 저장된 것을 제일 먼저 꺼냄
  • 위가 뚫린, 밑이 막힌 상자
  • 저장(push), 추출(pop)
  • 순차적인 데이터 저장 추출을 하기 때문에 배열로 구현하면 좋음






  • FIFO구조, 처음 저장된 것을 제일 먼저 꺼냄
  • 동굴과 같은 구조, 줄서기
  • 양쪽이 뚫린 구조
  • 저장(offer), 추출(poll)
  • 는 배열보다는 링크드 리스트로 구현하는 것이 편리








스택과 큐의 메서드


  • Stack
메서드 설명
boolean empty() Stack이 비어있는지 확인
Object peek() Stack의 맨 위에 저장된 객체를 반환, pop()과 달리 Stack에서 객체를 꺼내지 않음(비었을 때는 EmptyStackException이 발생)
Object pop() Stack의 맨 위에 저장된 객체를 꺼내어 반환(비었을 때 EmptyStackException 발생)
Object push(Object item) Stack에 객체(item)를 저장
int search(Object obj) Stack에서 주어진 객체(o)를 찾아서 그 위치를 반환, 못찾으면 -1을 반환(배열과 달리 위치는 1부터 시작)
import java.util.Stack;

Stack st = new Stack();

st.push(1);
System.out.println(st.peek()); // 1, 반환만

System.out.println(st.pop()); // 1, 꺼내짐
System.out.println(st.pop()); // 비어있는 Stack에서 pop을 사용하면 Exception발생


> 1
> 1

> Exception in thread "main" java.util.EmptyStackException
     at java.base/java.util.Stack.peek(Stack.java:101)
     at java.base/java.util.Stack.pop(Stack.java:83)
     at MyClass.main(MyClass.java:13)


  • Queue
메서드 설명
boolean add(Object obj) 지정된 객체를 Queue에 추가, 성공하면 true를 반환, 저장공간이 부족하면 IllgalStateException 발생
Object remove() Queue에서 객체를 꺼내 반환, 비어있으면 NoSuchElementException 발생
Object element() 삭제없이 요소를 읽어옴, peek과 달리 Queue가 비어있을 때 NoSuchElementException이 발생
boolean offer(Object obj) Queue에 객체를 저장, 성공하면 true 실패하면 false 반환
Object poll() Queue에서 객체를 꺼내 반환, 비어있으면 null을 반환
Object peek() 삭제없이 요소를 읽어옴, Queue가 비어있을 때 null을 반환
import java.util.LinkedList;
import java.util.Queue;

Queue q = new LinkedList(); // Queue는 interface로 되어 있기 때문에 바로 객체를 생성할 수 없음, Queue를 구현한 클래스를 활용하여 객체 생성

q.offer(0);
q.offer(1);
q.offer(2);

System.out.println(" = Queue = ");
while(!q.isEmpty()){
  System.out.println(q.poll()) // 큐에서 요소를 하나씩 꺼내어 반환
}


> = Queue = 
> 0
> 1
> 2


스택과 큐의 활용

  • 스택

    • 수식계산, 수식괄호검사

      • $((3+2)*8)/2$
    • 워드프로세서의 undo/redo

    • 웹브라우저의 뒤로가기 / 앞으로가기

    • 최근 사용 문서
    • 인쇄작업 대기목록
    • 버퍼(buffer)
1. 스택 예시

import java.util.*;

class Ex{
  public static void main(String[] args){
    if (args.length != 1){
      System.out.println("Usage:java Ex \"EXPRESSION\"");
      System.out.println("Example: java Ex \"((2+3)*1)+3\"");
      System.exit(0);
    }

    Stack st = new Stack();
    String expression = args[0];

    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("괄호가 일치합니다.");
      }else{
        System.out.println("괄호가 일치하지 않습니다.");
      }

    }catch(EmptyStackException e){
      System.out.println("괄호가 일치하지 않습니다.");
    }
  }
}


> expression:((2+3)*1)+2
> 괄호가 일치합니다.

1. 큐 예제

import java.util.*;

class Ex{
  static Queue q = new LinkedList();
  static final int MAX_SIZE = 10;

  public static void main(String[] args){
    System.out.println("help를 입력하면 도움말을 얻을 수 있습니다.");

    while(true){
      System.out.print(">>");

      try{
        Scanner sc = 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 - 도움말을 보여줍니다.");
          System.out.println(" q 또는 Q - 프로그램을 종료합니다.");
          System.out.println(" history - 최근에 입력한 명령어를 " + MAX_SIZE +"개 보여줍니다.");
        } else if(input.equalsIgnoreCase("history")){
          save(input);


        LinkedList lst = (LinkedList)q;
        final int SIZE = lst.size();
        for(int i = 0; i<SIZE; i++){
          System.out.println((i+1)+"."+lst.get(i));
          }

        } else{
          save(input);
          System.out.println(input);
        }

      } catch(Exception e){
        System.out.println("입력 오류입니다.");
      }
    }
  }
  public static void save(String input){
    if (!"".equals(input)){
      q.offer(input);
    }

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


Iterator, ListIterator, Enumeration

  • 컬렉션에 저장된 데이터를 읽어올 때 사용하는 인터페이스
  • Enumeration은 Iterator의 구버전
  • ListIterator는 Iterator의 접근성을 향상시킨 것(단방향 -> 양방향)(사용을 잘 안함)
  • Iterator를 가장 많이 사용, 데이터를 읽어오는 방법을 표준화했기 때문에
    • List -> Set으로 바꿨을 때 데이터 읽는 방법이 달라짐
    • Iterator를 사용하면 자료구조가 바뀌어도 쉽게 데이터를 읽을 수 있음

Iterator 메서드

메서드 설명
boolean hasNext() 읽어 올 요소가 남아있는지 확인, 있으면 true, 없으면 false
Object next() 다음 요소를 읽어옴, next()를 호출하기 전에 hasNext()를 호출하여 요소가 있는지 확인 후 사용하는 것이 안전
void remove() next()로 읽어 온 요소를 삭제, next()를 호출한 다음 remove()를 호출해야 함
void forEachRemaining(Consummer<? super E> action) 컬렉션에 남아있는 요소들에 대해 지정된 작업(action)을 수행, 람다식을 사용하는 디폴트 메서드(JDK1.8부터 추가)


Enumeration (Iterator와 비슷)

메서드 설명
boolean hasMoreElements() 읽어 올 요소가 남아있는지 확인, 있으면 true, 없으면 false반환 (Iterator의 hasNext()와 같음)
Object nextElement() 다음 요소를 읽어옴, nextElement()를 호출하기 전에 hasMoreElements()를 호출하여 요소가 남아있는지 확인 후 사용하는 것이 안전 (Iterator의 next()와 같음)
1. Iterator의 구조와 사용법

public interface Collection{
  ...
  public Iterator iterator();
  ...
}


List lst = new ArrayList();
Iterator it = lst.iterator();

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

----------------------------
2. 예시

class Ex{
  public static void main(String[] args){
    ArrayList lst = new ArrayList();
    Collection c = new TreeSet(); // TreeSet class(구현체)를 사용했지만 Collection이라는 참조변수를 썼기 때문에 공통된 처리를 할 수 있다.
    lst.add(1);
    lst.add(2);
    lst.add(3);
    lst.add(4);
    lst.add(5);

    Iterator it = lst.iterator(); // 한번만 읽는다

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

    for(int i = 0; i<lst.size();i++){ // 만약에 TreeSet()으로 한다면 get이란 메서드가 없기 때문에 객체에 따라 이 for문은 사용할 수 없을 수도 있다. 이 때 공통된 메서드를 가진 인터페이스로,  Collection으로 참조변수를 생성한다면 더 유연한 코드를 만들 수 있다.
      Object obj = lst.get(i);
      System.out.println("obj = " + obj);
    }
  }
}


> 1
> 2
> 3
> 4
> 5


Map과 Iterator

  • Map에는 iterator()가 없음 (Collection을 상속받고 있지 않아서)
  • Collection <- list, set
  • keySet()-Set, entrySet()-Set,values()-Collection를 호출해서 iterator()를 사용해야 함

public interface Collection{
  ...
  public Iterator iterator();
  ...
}

------------------------------

1. Map에서 iterator() 사용하는 예시

Map m = new HashMap();
Iterator it = m.entrySet().iterator();

Set s = m.entrySet();
Iterator it = s.iterator();


Arrays

  • 배열을 다루기 편리한 메서드(static) 제공
  • 배열의 출력 : toString()
static String toString(boolean[] b);
static String toString(byte[] b);
static String toString(char[] c);
static String toString(short[] s);
static String toString(int[] i);
static String toString(long[] l);
static String toString(float[] f);
static String toString(double[] d);
static String toString(Object[] o);

  • 배열의 복사 : copyOf(), copyOfRange();
  • 새로운 배열을 생성
    • System.arraycopy(original, copy);
int[] arr = {0,1,2,3,4};
int[] arr2 = Arrays.copyOf(arr, arr.length); // arr2 = [0,1,2,3,4]
int[] arr3 = Arrays.copyOf(arr, 3); // arr3 = [0,1,2];
int[] arr4 = Arrays.copyOf(arr, 7); // arr4 = [0,1,2,3,4,0,0];
int[] arr5 = Arrays.copyOfRange(arr, 2, 4); // arr5 = [2,3] 4는 x
int[] arr6 = Arrays.copyOfRange(arr, 0, 7); // arr6 = [0,1,2,3,4,0,0] 

  • 배열 채우기 : fill(), setAll()
int[] arr = new int[5];
Arrays.fill(arr,9);
Arrays.setAll(arr, (i) -> (int)(Math.random()*5)+1); // arr = [1,5,2,1,1], 람다식 난수생성

  • 배열의 정렬과 검색 : sort(), binarySearch()(배열에서 해당 값을 찾아서 idx 반환, 정렬이 되어 있을 때만)
int[] arr = {3,2,0,1,4};
int idx = Arrays.binarySearch(arr, 2); // idx = -5  잘못된 결과

Arrays.sort(arr); // 배열 정렬
System.out.println(Arrays.toString(arr)); // [0,1,2,3,4]
int idx = Arrays.binarySearch(arr, 2); // idx = 2

순차탐색

시작 7 1 6 9 5 3 8 4 10 2
  • 원하는 데이터를 앞에서부터 순차적으로 검색하는 것을 순차검색이라고 함, O($N$)
    • 4를 찾는다고 가정
        1. 7부터 배열의 끝까지를 완전검색을 진행

이진탐색

1 2 3 4 5 6 7 8 9 10
  • 원하는 데이터를 정렬된 배열에서 찾는데 계속적으로 절반씩 배열을 나눠가며 해당 데이터를 찾는 방법, O($log_2N$)
    • 9를 찾는다고 가정
        1. 5가 9보다 작으니 5 이하의 값은 버린다.
        1. 6~10의 가운데 8이 9보다 작기 때문에 8이하의 값은 버린다.
        1. 9~10 중 원하는 데이터를 찾는다.


  • 다차원 배열의 출력 - deepToString()
int[] arr = {0,1,2,3,4};
int[][] arr2D = {{11,12}, {21,22}};

System.out.println(Arrays.toString(arr));
System.out.println(Arrays.deepToString(arr2D));


> [0,1,2,3,4]
> [[11,12], [21,22]];

  • 다차원 배열의 비교 - deepEquals()
String[][] str2D = new String[][]{{"aaa","bbb"},{"ccc","ddd"}};
String[][] str2D2 = new String[][]{{"aaa","bbb"},{"ccc","ddd"}};

System.out.println(Arrays.equals(str2D, str2D2)); 
System.out.println(Arrays.deepEquals(str2D, str2D2)); 


> false
> true 

  • 배열을 List로 변환 : asList(Object o)
List lst = Arrays.asList(new Integer[]{1,2,3,4,5}); // lst = [1,2,3,4,5]
List lst = Arrays.asList(1,2,3,4,5); // lst = [1,2,3,4,5]
lst.add(6); // List는 읽기 전용, UnsupportedOpperationException 에러 발생

List lst = new ArrayList(Arrays.asList(1,2,3,4,5)); // 이렇게 하면 ArrayList이기 때문에 add 가능

  • 람다와 스트림(14장)관련 : parallelXXX(),spliterator(),stream()


Comparator와 Comparable

  • 객체 정렬에 필요한 메서드(정렬기준 제공)를 정의한 인터페이스

  • Comparator
    • 기본 정렬기준 외에 다른 기준으로 정렬하고자할 때 사용

  • Comparable

    • 기본 정렬기준을 구현하는데 사용

      • 0 : 같다
      • 양수 : 왼쪽이 크다
      • 음수 : 오른쪽이 크다

public interface Comparator{
  int compare(Object obj1, Object obj2); // obj1, obj2 두 객체 비교
  boolean equals(Object obj); // equals를 오버라이딩하라는 뜻
}

public interface Comparable{
  int compareTo(Object obj); // 주어진 객체를 자신과 비교
}

---------------------------------------------

public final class Integer extends Number implements Comparable{
  ...
  public int compareTo(Integer anotherInteger){
    int v1 = this.value;
    int v2 = anotherInteger.value;

    // 같으면 0 , 오른쪽이 크면 -1, 왼쪽이 크면 1
    return (v1 < v2 ? -1 : (v1==v2 ? 0 : 1));
  }
}

--------------------------------------------

class Ex{
  public static void main(String[] args){
    String[] strArr = {"cat","Dog","lion","tiger"};

    Arrays.sort(strArr); // String의 Comparable구현에 의한 정렬
    System.out.println("strArr = " + Arrays.toString(strArr));

    Arrays.sort(strArr, String.CASE_INSENSITIVE_ORDER); // 대소문자 구분 안함
    System.out.printlm("strArr = " + Arrays.toString(strArr));

    Arrays.sort(strArr, new Descending()); // 역순 정렬
    System.out.printlm("strArr = " + Arrays.toString(strArr));
  }
}

class Descending implements Comparator{
  public int compare(Object obj1, Object obj2){
    if ( obj1 instanceof Comparable && obj2 instanceof Comparable){
      Comparable c1 = (Comparable) obj1;
      Comparable c2 = (Comparable) obj2;
      return c1.compareTo(c2) * -1; // -1을 곱해 기본 정렬방식의 역으로 진행
      // 또는 c2.compareTo(c1)으로 해도 됨

    }
    return -1;
  }
}


> strArr = [Dog, cat, lion, tiger]
> strArr = [cat, Dog, lion, tiger]
> strArr = [tiger, lion, cat, Dog]


HashSet

  • Set인터페이스를 구현한 대표적인 컬렉션 클래스

  • 중복 x, 순서 x


    • HashSet

      • 대표적인 Set구현체(HashSet, TreeSet)
      • 순서를 유지하려면, LinkedHashSet클래스를 사용
    • TreeSet

      • 범위 검색과 정렬에 유리한 컬렉션 클래스
      • HashSet보다 데이터 추가, 삭제에 시간이 더 걸림

주요 메서드와 예제

1. HashSet() 주요 메서드

HashSet() // 기본생성자
HashSet(Collection c) // 객체를 저장하는생성자 
HashSet(int initialCapacity) // 초기 용량
HashSet(int initialCapacity, float loadFactor) // 언제 저장공간을 늘릴 것인가

boolean add(Object o) // 객체 추가
boolean addAll(Collection c) // 컬렉션 추가(합집합)
boolean remove(Object o) // 객체 삭제
boolean removeAll(Collection c) //컬렉션 삭제(교집합)
boolean retainAll(Collection c) // 조건부 삭제(차집합)
void clear() // 모두 삭제

boolean contains(Object o) // 객체 포함
boolean containsAll(Collection c) // 컬렉션의 요소들이 모두 포함되어 있는지
Iterator iterator() 

boolean isEmpty()
int size() // 저장된 객체의 수
Object[] toArray() // 객체배열로 반환
Object[] toArray(Object[] a)

---------------------------------------------------------

2. HashSet()의 예제

class Ex{
  public static void main(String[] args){
    Object[] objArr = {"1", Integer.valueOf(1), "2","2","3","3","4","4","4"};
    Set s = new HashSet();

    for (int i = 0; i < objArr.length; i++){
      s.add(objArr[i])
    }

    System.out.println(s);

    Iterator it = s.iterator();

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


> [1, 1, 2, 3, 4] // index(0)의 1은 문자열 1, index(1)의 1은 Integer 1, 순서보장 x
> 1
> 1
> 2
> 3
> 4

-------------------------------------------------

3. 예제 2

class Ex2{
  public static void main(String[] args){
    Set s =  new HashSet(); // HashSet 객체 생성

    for(int i = 0; s.size() < 6; i++){ // s의 저장된 객체 수가 6이 될 때까지 
      int num = (int)(Math.random()*45)+1; // 1~45까지 난수를 생성
      s.add(new Integer(num)); // set에 저장
    }

    List lst = new LinkedList(s); // set은 정렬할 수 없기 때문에 List로 새로운 객체 생성
    Collections.sort(lst); // 정렬
    System.out.println(lst); 
  }
}


> [5, 19, 22, 29, 33, 36]


HashSet 예제 3

  • HashSet은 객체를 저장하기전에 기존에 같은 객체가 있는지 확인, 같은 객체가 없으면 저장, 있으면 저장하지 않음
  • boolean add(Object o)는 저장할 객체의 equals()와 hashCode()를 호출
  • equals()와 hashCode()는 Object에서 있고, 기본적으로 class는 extends Object가 되어있음
  • equals()와 hashCode()가 오버라이딩 되어 있지 않다면 해주어야 함

1. equals와 hashCode 오버라이딩 예제 1

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)) return false;

    Person tmp = (Person)obj; // Object에는 name과 age가 없기에 형변환 해야함
    return name.equals(tmp.name) && age == tmp.age;
  }



  public int hashCode(){
    return (name+age).hashCode();
    // return Objects.hash(name,age);
  }
}


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

    s.add("abc");
    s.add("abc");
    s.add(new Person("David",20));
    s.add(new Person("David",20));

    System.out.println(s);
  }
}


> [abc, David:20, David:20] // equals()랑 hashCode()를 오버라이딩하지 않으면 중복되어 나옴
> [abc, David:20] // 오버라이딩을 했을 때 나온 결과

--------------------------------------------------

2. 집합 사용 예시(합, 교, 차)

class Ex2{
  public static void main(String[] args){
    HashSet setA = new HashSet();
    HashSet setB = new HashSet();
    HashSet setHab = new HashSet();
    HashSet setKyo = new HashSet();
    HashSet setCha = new HashSet();

    setA.add("1"); setA.add("2"); setA.add("3");
    setA.add("4"); setA.add("5");

    setB.add("4"); setB.add("5"); setB.add("6");
    setB.add("7"); setB.add("8");

    System.out.println("A = " + setA);
    System.out.println("B = " + setB);

    Iterator itB = setB.iterator();

    while(itB.hasNext()){
      Object tmp = itB.next();
      if(setA.contains(tmp)){
        setKyo.add(tmp);
      }
    }

    Iterator itA = setA.iterator();
    while(itA.hasNext()){
      Object tmp = itA.next();
      if(!setB.contains(tmp)){
        setCha.add(tmp);
      }
    }

    itA = setA.iterator();
    itB = setB.iterator();

    while(itA.hasNext()){
      setHab.add(itA.next());
    }    

    while(itB.hasNext()){
      setHab.add(itB.next());
    }    


    System.out.println("A ∩ B : " + setKyo );
    System.out.println("A ∪ B : " + setHab );
    System.out.println("A - B : " + setCha );

  }
}



> A = [1, 2, 3, 4, 5]
> B = [4, 5, 6, 7, 8]
> A ∩ B : [4, 5]
> A ∪ B : [1, 2, 3, 4, 5, 6, 7, 8]
> A - B : [1, 2, 3]

----------------------------------------------

3. 간단한 집합 예시

class Ex3{
  public static void main(String[] args){
    HashSet setA = new HashSet();
    HashSet setB = new HashSet();
    HashSet setHab = new HashSet();
    HashSet setKyo = new HashSet();
    HashSet setCha = new HashSet();

    setA.add("1"); setA.add("2"); setA.add("3");
    setA.add("4"); setA.add("5");

    setB.add("4"); setB.add("5"); setB.add("6");
    setB.add("7"); setB.add("8");

    System.out.println("A = " + setA);
    System.out.println("B = " + setB);

    setA.retainAll(setB) // 교집합 공통된 부분만 남기고 삭제
    setA.addAll(setB) // 합집합, A에 B의 모든 요소 추가 (중복 제외)
    setA.removeAll(setB) // 차집합, A에서 B와 공통 요소 제거

  }
}


TreeSet


  • 이진 탐색 트리(Binary Search Tree)로 구현, 범위 탐색과 정렬에 유리
  • 이진 트리는 모든 노드가 최대 2개의 하위 노드를 갖는 트리
  • 각 요소(node)가 나무(tree)형태로 연결(LinkedList의 변형)
  • 범위 탐색, 정렬




class TreeNode{
  TreeNode left;
  Object element;
  TreeNode right;
}


이진 탐색 트리(Binary Search Tree)

  • 부모보다 작은 값은 왼쪽, 큰 값은 오른쪽에 저장
  • 데이터가 많아질 수록 추가, 삭제에 시간이 더 걸림(비교 횟수 증가)





TreeSet 데이터 저장 과정

  • boolean add(Object o)
    • HashSet은 equals, hashCode로 비교
    • TreeSet은 compare을 호출하여 비교

  • 7,4,9,1,5 을 저장할 때





TreeSet의 생성자와 주요 메서드

생성자 또는 메서드 설명
TreeSet() 기본 생성자
TreeSet(Collection c) 주어진 컬렉션을 저장하는 TreeSet을 생성
TreeSet(Comparator comp) 주어진 정렬기준으로 정렬하는 TreeSet을 생성
Object first() 정렬된 순서에서 첫 번째 요소를 반환
Object last() 정렬된 순서에서 마지막 요소를 반환
Object ceiling(Object o) 지정된 객체와 같은 객체를 반환, 없으면 큰 값을 가진 객체 중 제일 가까운 값의 객체를 반환, 없으면 null
Object floor(Object o) 지정된 객체와 같은 객체를 반환, 없으면 작은 값을 가진 객체 중 가장 가까운 값의 객체를 반환, 없으면 null
Object higher(Object o) 지정된 객체보다 큰 객체 중 제일 가까운 값을 반환, 없으면 null
Object lower(Object o) 지정된 객체보다 작은 객체 중 가장 가까운 값을 반환, 없으면 null
SortedSet subSet(Object fromElement, Object toElement) 범위 검색의 결과를 반환(끝 범위는 포함하지 않음)
SortedSet headSet(Object toElement) 지정된 객체보다 작은 값의 객체를 반환
SortedSet tailSet(Object fromElement) 지정된 객체보다 큰 값의 객체를 반환
1. TreeSet 예제 1

class Ex{
  public static void main(String[] args){
    Set s = new TreeSet(); // 범위 검색 및 정렬에 장점, 정렬필요없음
    Set hs = new HashSet();

    for (int i = 0; s.size()<6; i++){ // set의 size가 6일 때까지 (0~5)
      int num = (int)(Math.random()*45)+1; // 1~45의 범위의 난수 생성
      s.add(num); // Integer class에 정렬기준이 있기 때문에 정렬이 된다.
      hs.add(num);
    }

    System.out.println(s);
    System.out.println(hs);
  }
}



> [17, 21, 33, 36, 39, 43] // 정렬이 되어 있음
> [33, 17, 36, 21, 39, 43] // 정렬이 되어 있지 않음

--------------------------------------------

2. TreeSet 예제 2

class Ex2{
  public static void main(String[] args){
    Set s = new TreeSet(new TestCompare()); // 정렬 기준이 꼭 필요함, 
    s.add(new Test()); // Test class 내에 정렬기준이 있다면 위는 생략가능
    System.out.println(s);
  }
}

class Test{}

class TestCompare implements Comparator{
  public int compare(Object o1, Object o2){
    return 0;
  }
}



> [Test@41975e01]
--------------------------------------------------------

3. TreeSet 예제 3

class Ex3{
  public static void main(String[] args){
    TreeSet s = new TreeSet();

    String from = "b";
    String to = "d";

    s.add("abc"); s.add("alien"); s.add("bat"); s.add("car");
    s.add("Car"); s.add("disc"); s.add("dance"); s.add("dzzzz");
    s.add("dZZZZ"); s.add("elephant"); s.add("elevator"); s.add("fan");
    s.add("flower");

    System.out.println(s);
    System.out.println("range search from " + from + " to " + to);
    System.out.println("result1 : " + s.subSet(from,to) );
    System.out.println("result2 : " + s.subSet(from, to + "zzz"));

  }
}


> [Car, abc, alien, bat, car, dZZZZ, dance, disc, dzzzz, elephant, elevator, fan, flower]
> range search from  b to d
> result1 : [bat, car]
> result2 : [bat, car, dZZZZ, dance, disc]

-------------------------------------------------------------------

4. TreeSet 예제 4

class Ex4{
  public static void main(String[] args){
    TreeSet s = new TreeSet();
    int[] score = {50,70,60,80,98,100,10};

    for(int i = 0; i<score.length; i++){
      s.add(new Integer(score[i]));
    }
    System.out.println("50보다 큰 값 : " + s.tailSet(50));
    System.out.println("50보다 작은 값 : " + s.headSet(50));

  }
}


> 50보다 큰 값 : [50, 60, 70, 80, 98, 100]
> 50보다 작은 값 : [10]


TreeSet 범위 검색





  • Tree 순회
    • 전위 순회
    • 후위 순회
    • 중위 순회
    • 레벨 순회


HashMap과 HashTable


  • Map인터페이스를 구현, 데이터를 키와 값의 쌍으로 저장
  • 순서 x, 중복 x(키 x, 값 o)
  • HashMap(동기화 x)은 HashTable(동기화 o)의 신버전
  • 대표적으로 키와 쌍의 데이터를 쓰기 위해선 HashMap과 TreeMap을 많이 사용
  • 순서를 유지하고 싶다면, LinkedHashMap을 사용
  • 해싱(hashing)기법으로 데이터를 저장, 데이터가 많아도 검색이 빠름

HashMap


1. HashMap class 구조

public class HashMap extends AbstractMap implements Map, Clonable, Serializable{
  transient Entry[] table;
  ...

  static class Entry implements Map.Entry{
    final Object key;
    Object value;
    ...
  }
}

--------------------------------------

2. HashMap 사용 예

HashMap map = new HashMap();
map.put("myId", "1234");
map.put("myPwd", "1234555");
map.put("myPwd", "12345");
System.out.println(map);



> {myId=1234, myPwd=12345}


HashTable

  • 해시함수로 해시테이블에 데이터를 저장 및 읽는 자료구조
  • 해시테이블은 배열과 링크드리스트가 조합된 형태





  • HashTable에서 데이터를 읽는 과정
  1. 키로 해시함수를 호출해서 해시코드를 얻음
  2. 해시코드(인덱스)에 대응하는 링크드리스트를 배열에서 찾음
  3. 링크드리스트에서 키와 일치하는 데이터를 찾음
    • 해시함수는 같은 키에 대해 항상 같은 해시코드를 반환해야함
    • 서로 다른 키일지라도 같은 값의 해시코드를 반환할 수 있음


  • HashMap의 주요 메서드
메서드 설명
HashMap() 생성자
HashMap(int initialCapacity) 크기를 지정해주는 생성자
HashMap(int initialCapacity, float loadFactor) 크기와 언제 배열을 늘리지 알려주는 생성자
HashMap(Map m) Map을 매개변수로 HashMap을 생성
Object put(Object key, Object value) HashMap에 새로운 데이터를 추가(key, value 쌍)
void putAll(Map m) Map 객체의 전체 요소를 추가
Object remove(Object key) 지정한 key에 해당하는 데이터를 삭제
Object replace(Object key, Object value) 지정된 키에 해당하는 데이터를 변경
boolean replace(Object key, Object oldValue, Object newValue) 지정된 키에 해당하는 지난 데이터를 새로운 데이터로 수정
Set entrySet() 키와 값의 쌍으로 이루어진 Set을 반환
Set keySet() 키로만 구성된 Set을 반환
Collection values() 값으로만 구성된 Collection을 반환
Object get(Object key) 지정한 키를 넣으면 그 키에 해당하는 값(value)가 반환
Object getDefault(Object key, Object defaultVale) 만약에 키가 없을 때 지정한 값으로 반환
boolean containsKey(Object key) 해당하는 키가 존재하는지 확인
boolean containsValue(Object value) 해당하는 값이 존재하는지 확인
int size() 저장된 객체의 수
boolean isEmpty() 비어있는지 확인
void clear() HashMap에 모든 데이터를 삭제
Object clone() 복사
class Ex{
  public static void main(String[] args){
    HashMap map = new HashMap();

    map.put("김자바", 100);
    map.put("강자바", 60);
    map.put("박자바", 70);
    map.put("이자바", 40);
    map.put("위자바", 80);

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

    while(it.hashNext()){
      Map.Entry e = (Map.Entry)it.next();
      System.out.println("이름 : " + e.getKey() + " 점수 : " + e.getValue());
    }

    set = map.keySet();
    System.out.println("참가자 명단 : " + set);

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

    int total = 0;

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

    System.out.println("총점 : " + total);
    System.out.println("평균 : " + (float)total/set.size());
    System.out.println("최고점수 : " + Collections.max(values));
    System.out.println("최저점수 : " + Collections.min(values));

  }
}



> 이름 : 김자바 점수 : 100
> 이름 : 박자바 점수 : 70
> 이름 : 강자바 점수 : 60
> 이름 : 위자바 점수 : 80
> 이름 : 이자바 점수 : 40
> 참가자 명단 : [김자바, 박자바, 강자바, 위자바, 이자바]
> 총점 : 350
> 평균 : 70.0
> 최고점수 : 100
> 최저점수 : 40

-------------------------------------------------------------

class Ex2{
  public static void main(String[] args){
    String[] data = {"a","c","d","a","a","d","b","c"};

    HashMap map = new HashMap();

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

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

    while(it.hasNext()){
      Map.Entry entry = (Map.Entry)it.next();
      int value = (int)entry.getValue();
      System.out.println(entry.getKey() + " : " + "*".repeat(value) + " " + value); // java 11부터는 "".repeat() 가능
    }
  }
}



> a : *** 3
> b : * 1
> c : ** 2
> d : ** 2


Collections 클래스

  • 컬렉션을 위한 메서드(static) 제공
  • Objects, Arrays, Collections
  1. 컬렉션 채우기
    • fill(), copy(), sort(), binarySearch() 등

  1. 컬렉션 동기화

    • syncronizedXXX();

      • static Collection sysncronizedCollection(Collection c);
      • static List sysncronizedList(List l);
      • static Set sysncronizedSet(Set s);
      • static Map sysncronizedMap(Map m);
      • static SortedSet sysncronizedSortedSet(SortedSet ss);
      • static SortedMap sysncronizedSortedMap(SortedMap sm);
    • List syncList = Collections.sysnronizedList(new ArrayList());


  1. 변경불가(readOnly) 컬렉션 만들기
    • unmodifiableXXX()
      • static Collection unmodifiableCollection(Collection c)
      • static List unmodifiableList(List l)
      • static Set unmodifiableSet(Set s)
      • static Map unmodifiableMap(Map m)
      • static NavigableSet unmodifiableNavigableSet(NavigableSet ns)
      • static SortedSet unmodifiableSortedSet(SortedSet ss)
      • static NavigableMap unmodifiableNavigableMap(NavigableMap nm)
      • static SortedMap unmodifiableSortedMap(SortedMap sm)

  1. 싱글톤 컬렉션 만들기
    • singletonXXX()
      • static List singletonList(Object o)
      • static Set singleton(Object o) // singletonSet이 아님
      • static Map singletonMap(Object key, Object value)

  1. 한 종류의 객체만 저장하는 컬렉션 만들기
    • checkedXXX()
      • static Collection checkedCollection(Collection c, Class type)
      • static List checkedList(List l, Class type)
      • static Set checkedSet(Set s, Class type)
      • static Map checkedMap(Map m, Class keyType, Class valueType)
      • static Queue checkedQueue(Queue queue, Class type)
      • static NavigableSet checkedNavigableSet(NavigableSet s, Class type)
      • static SortedSet checkedSortedSet(SortedSet ss, Class type)
      • static NavigableMap checkedNavigableMap(NavigableMap nm, Class type)
      • static SortedMap checkedSortedMap(SortedMap sm, Class keyType, Class valueType)
List lst = new ArrayList();
List checkedList = checkedList(lst,String.class); // String 타입만 저장 가능
checkedList.add("abc");
checkedList.add(new Integer(10)); // error, ClassCastException 발생
import static java.util.Collection.*;

class Ex{
  public static void main(String[] args){
    List lst = new ArrayList();
    System.out.println(lst);

    addAll(lst, 1,2,3,4,5);
    System.out.println(lst);

    rotate(lst, 1);
    System.out.println(lst);

    swap(lst,0,2);
    System.out.println(lst);

    shuffle(lst);
    System.out.println(lst);

    sort(lst,reverseOrder());
    System.out.println(lst);

    sort(lst);
    System.out.println(lst);

    int idx = binarySearch(lst,3);
    System.out.println(idx);

    System.out.println("max : " + max(lst));
    System.out.println("min : " + min(lst));
    System.out.println("min : " + max(lst, reverseOrder()));

    fill(lst,9);
    System.out.println("fill : " + lst);

    List newList = nCopies(lst.size(), 2); // list와 같은 크기의 새로운 list를 생성하고 2로 채움
    System.out.println("newList : " + newList);
    System.out.println("List : " + lst);

    System.out.println(disjoint(newList, lst)); // 공통요소가 없으면 true

    replaceAll(lst, 9, 1);
    System.out.println("replace list : " + lst);

    Enumeration e = enumeration(lst);
    ArrayList list2 = list(e);

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

  }
}



> []
> [1, 2, 3, 4, 5]
> [5, 1, 2, 3, 4]
> [2, 1, 5, 3, 4]
> [1, 5, 4, 3, 2]
> [5, 4, 3, 2, 1]
> [1, 2, 3, 4, 5]
> 2
> max : 5
> min : 1
> min : 1
> fill : [9, 9, 9, 9, 9]
> newList : [2, 2, 2, 2, 2]
> List : [9, 9, 9, 9, 9]
> true
> replace list : [1, 1, 1, 1, 1]
> list2 : [1, 1, 1, 1, 1]





  • 자바의 정석 챕터 11에서는 컬렉션의 정의와 종류, 스택과 큐, Iterator, ListIterator, Enumeration, ArrayList, LinkedList, treeSet, Hashing, hashMap, hashTable, Collections을 배웠습니다.

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함