본문 바로가기

STUDY/국비과정

[JAVA 웹 개발 공부] 국비지원 26일차 - 컬렉션(collection), Iterator, ArrayList

컬렉션(collection)

 

1. 컬렉션

컬렉션은 애플리케이션의 작성을 도와주는 중요한 도구이다. 컬렉션은 자료를 저장하기 위한 구조이다.

대부분의 프로그램은 자료를 저장하여야 하고 따라서 어떤 자료구조를 사용할 것인지를 결정하여야 한다.

많이 사용되는 자료구조로는 리스트(list), 스택(stack), 큐(queue), 집합(set), 해쉬 테이블(hash table) 등이 있다. 

컬렉션은 데이터를 저장하는 자료구조이다. 컬렉션은 제네릭 기법으로 구현되어 있기 때문에 어떠한 타입의 데이터도 저장할 수 있다.

 

2. 컬렉션의 종류

자바는 컬렉션 인터페이스와 컬렉션 클래스로 나누어서 제공한다. 인터페이스와 클래스들은 모두 java.util 패키지에 포함되어 있다. 

 

*컬렉션 인터페이스

인터페이스 설명
Collection 모든 자료구조의 부모 인터페이스로서 객체의 모임을 나타낸다.
Set 집합(중복된 원소를 가지지 않는)을 나타내는 자료구조
List 순서가 있는 자료구조로 중복된 원소를 가질 수 있다.
Map 키와 값들이 연관되어 있는 사전과 같은 자료구조
Queue 극장에서의 대기줄과 같이 들어온 순서대로 나가는 자료구조

List는 동적 배열을 정의하고 있다. Set은 집합을 정의하고 있으며, Map은 키가 주어지면 값을 반환하는 사전과 같은 자료구조를 정의하고 있다. 사용자는 자신이 인터페이스를 구현하여도 되고(고급 사용자), 아니면 자신의 필요에 맞는 컬렉션 클래스를 선택하여 사용하면 된다.

 

3. 컬렉션의 특징

(1) 컬렉션은 제네릭을 사용한다.

(2) 컬렉션에는 int나 double과 같은 기초 자료형은 저장할 수 없다. 클래스만 가능하다. 기초 자료형을 클래스로 감싼 랩퍼 클래스인 Integer나 Double은 사용할 수 없다.

(3) 기본 자료형을 저장하면 자동으로 랩퍼 클래스의 객체로 변환된다. 이것을 오토박싱(auto boxint)이라고 한다.

 

4. 컬렉션 인터페이스의 주요 메소드

메소드 설명 반환타입
add(Object o)
addAll(Collection c)
지정된 객체(o) 또는 Collection(c) 의 객체들을 Collection에 추가한다. boolean
clear() Collection의 모든 객체를 삭제한다. void
contains(Object o)
containsAll(Collection c)
지정된 객체(o) 또는 Collection의 객체들이 Collection에 포함되어 있는지 확인한다. boolean
equals(Object o) 동일한 Collection인지 비교한다. boolean
hashCode() Collection의 hash code를 반환한다. int
isEmpty() Collection이 비어있는지 확인한다. boolean
iterator() Collection의 Iterator를 얻어서 반환한다. Iterator
remove(Object o) 지정된 객체를 삭제한다. boolean
removeAll(Collection c) 지정된 Collection에 포함된 객체들을 삭제한다. boolean
retainAll(Collection c) 지정된 Collection에 포함된 객체만을 남기고 다른 객체들은  Collection에서 삭제한다. 이 작업으로 인해 Collection에 변화가 있으면 true를 그렇지 않으면 false를 반환한다. boolean
size() Collection에 저장된 객체의 개수를 반환한다. boolean
toArray() Collection에 저장된 객체를 객체배열(Object[])로 반환한다. Object[]
toArray(Object[] a) 지정된 배열에 Collection의 객체를 저장해서 반환한다. Object[]

 

 

컬렉션의 모든 요소 접근하기

 

String[] a = new String[] { "A", "B", "C", "D", "E" };
List<String> list = Arrays.asList(a);

 

1. for문 사용

for (int i = 0; i < list.size(); i++) {
	System.out.println(list.get(i));
}

 

2. for-each문 사용

for (String s : list) {
	System.out.println(s);
}

 

3. Iterator(반복자) 사용

반복자는 특별한 타입의 객체로 컬렉션의 원소들을 접근하는 것이 목적이다.

ArrayList뿐만 아니라 반복자는 모든 컬렉션에 적용할 수 있다. 반복자는 java.util 패키지에 정의되어 있는 Iterator 인터페이스를 구현하는 객체이다. 

 

*Iterator 인터페이스에 정의된 메소드

메소드 설명
hasNext() 아직 방문하지 않은 원소가 있으면 true를 반환
next() 다음 원소를 반환
remove() 최근에 반환된 원소를 삭제

 

반복자를 사용하기 위해서는 먼저 ArrayList의 iterator() 메소드를 호출하여서 반복자 객체를 얻는다.

다음으로 반복자 객체의 hasNext()와 next() 메소드를 이용하여서 컬렉션의 각 원소들을 접근하게 된다.

String s;
Iterator e = list.iterator();
while(e.hasNext()) {
	s = (String)e.next(); // 반복자는 Object 타입을 반환
	System.out.println(s);
}

 

4. Stream 라이브러리를 이용하는 방법

forEach 메소드와 람다식을 사용한다. 

list.forEach((n) -> System.out.println(n));

 

 

ArrayList

 

ArrayList는 컬렉션 프레임웍에서 가장 많이 사용되는 컬렉션 클래스일 것이다. 

ArrayList는 List 인터페이스를 구현하기 때문에 데이터의 저장순서가 유지되고 중복을 허용한다는 특징을 갖는다.

ArrayList는 Object 배열을 이용해서 데이터를 순차적으로 저장한다. 배열에 더 이상 저장할 공간이 없으면 보다 큰 새로운 배열을 생성해서 기존의 배열에 저장된 내용을 새로운 배열로 복사한 다음에 저장된다.

메소드 설명
ArrayList() 크기가 10인 ArrayList를 생성
ArrayList(Collection c) 주어진 컬렉션이 저장된 ArrayList를 생성
ArrayList(int initialCapacity)0 지정된 초기용량을 갖는 ArrayList를 생성
boolean add(Object o) ArrayList의 마지막에 객체를 추가. 성공하면  true
void add(int index, Object element) 지정된 위치(index)에 객체를 저장
boolean addAll(Collection c) 주어진 컬렉션의 모든 객체를 저장한다.
boolean addAll(int index, Collection c) 지정된 위치부터 주어진 컬렉션의 모든 객체를 저장한다.
void clear() ArrayList를 완전히 비운다.
Object clone() ArrayList를 복제한다.
boolean contains(Object o) 지정된 객체(o)가 ArrayList에 포함되어 있는지 확인
void ensureCapacity(int minCapacity) ArrayList의 용량이 최소한 minCapacity가 되도록 한다.
Object get(int index) 지정된 위치(index)에 저장된 객체를 반환한다.
int indexOf(Object o) 지정된 객체가 저장된 위치를 찾아 반환한다.
boolean isEmpty() ArrayList가 비어있는지 확인한다.
Iterator iterator() ArrayList의 Iterator 객체를 반환
int lastIndexOf(Object o) 객체(o)가 저장된 위치를 끝부터 역방향으로 검색해서 반환
ListIterator listIterator() ArrayList의 ListIterator를 반환
ListIterator listIterator(int index) ArrayList의 지정된 위치부터 시작하는 ListIterator를 반환0
Object remove(int index) 지정된 위치(index)에 있는 객체를 제거한다.
boolean remove(Object o) 지정한 객체를 제거한다.(성공하면 true, 실패하면 false)
boolean removeAll(Collection c) 지정한 컬렉션에 저장된 것과 동일한 객체들을 ArrayList에서 제거한다.
boolean retainAll(Collection c) ArrayList에 저장된 객체 중에서 주어진 컬렉션과 공통된 것들만을 남기고 나머지는 삭제한다.
Object set(int index, Object element) 주어진 객체(element)를 지정된 위치(index)에 저장한다.
int size() ArrayList에 저장된 객체의 개수를 반환한다.
void sort(Comparator c) 지정된 정렬 기준(c)으로 ArrayList를 정렬
List subList(int fromIndex, int toIndex) fromIndex부터 toIndex사이에 저장된 객체를 반환한다.
Object[] toArray() ArrayList에 저장된 모든 객체들을 객체배열로 반환한다.
Object[] toArray(Object[] a) ArrayList에 저장된 모든 객체들을 객체배열 a에 담아 반환한다.
void trimToSize() 용량을 크기에 맞게 줄인다.(빈 공간을 없앤다.)

 

 

ArrayList 연습

 

*ArrayList 생성

import java.util.ArrayList;
import java.util.List;

public class Main {
	public static void main(String[] args) {
		List list = new ArrayList();
		list.add("ㅁㄴㅇㄹ");
		list.add(Integer.valueOf(100));
		list.add(500);
		list.add(Double.valueOf(45.12));
		
		System.out.println("현재원소개수: " + list.size()); // 현재원소개수: 4
		System.out.println(list.get(0)); // ㅁㄴㅇㄹ
	}
}

 

*ArrayList<Integer>

import java.util.ArrayList;
import java.util.List;

public class Main2 {
	public static void main(String[] args) {
		List<Integer> numberList = new ArrayList<Integer>();
		numberList.add(100);
		numberList.add(150);
		numberList.add(90);
		numberList.add(120);
		
		for (int i = 0; i < numberList.size(); i++) {
			System.out.println(numberList.get(i));
		}
		
		// 원소 합 구하기
		int sum = 0;
		for (int i = 0; i < numberList.size(); i++) {
			sum += numberList.get(i);
		}
		System.out.println(sum);
	}
}

 

*ArrayList<String>

import java.util.ArrayList;
import java.util.List;

public class Main3 {
	public static void main(String[] args) {
		// 여러개의 문자열 자료
		// 순서가 있는 번호로 관리
		// 크기가 동적으로 알아서 변화
		List<String> strList = new ArrayList<String>();
		strList.add("둘리");
		strList.add("바나나");
		strList.add("대한민국");
		strList.add("손흥민");
		
		for (int i = 0; i < strList.size(); i++) {
			System.out.println(strList.get(i));
		}
		
		for (String elem : strList) {
			System.out.println(elem);
		}
	}
}

 

*원소 변경, 원소 지우기

import java.util.ArrayList;
import java.util.List;

public class Main4 {
	public static void main(String[] args) {
		List<String> strList = new ArrayList<String>();
		strList.add("둘리");
		strList.add("바나나");
		strList.add("대한민국");
		strList.add("손흥민");
		
		// 원소 변경
		strList.set(0, "도우너");
		strList.set(1, "사과");
		
		// 원소 지우기
		strList.remove(2);
		System.out.println(strList.get(2));
		
		for (String elem : strList) {
			System.out.println(elem);
		}
	}
}

 

 

*두 배열 합치기

import java.util.ArrayList;
import java.util.List;

public class Main6 {
	public static void main(String[] args) {
		List<String> strList = new ArrayList<>();
		strList.add("가");
		strList.add("나");
		strList.add("다");
		strList.add("라");
		strList.add("마");
		
		// 원소 있는지 확인
		System.out.println(strList.contains("가")); // true
		System.out.println(strList.contains("바")); // false
		
		List<String> abcList = new ArrayList<>();
		abcList.add("A");
		abcList.add("B");
		abcList.add("C");
		
		// 배열 합치기
		strList.addAll(abcList);
		System.out.println(strList.toString()); // [가, 나, 다, 라, 마, A, B, C]
	}
}

 

*배열 비우기

strList.clear();
System.out.println(strList.size() == 0); //true
System.out.println(strList.isEmpty()); // true

 

*원소 값 정하여 배열 생성

List<Integer> list = new ArrayList<Integer>(Arrays.asList(1, 2, 3, 4, 5, 6));
System.out.println(list.size()); // 6
System.out.println(list); // [1, 2, 3, 4, 5, 6]

 

*배열 원소 추가 

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

list.add(0, 100);
System.out.println(list); // [100, 1, 2, 3, 4, 5, 6]

 

*원소 확인

boolean all = list.containsAll(new ArrayList<>(Arrays.asList(1, 2, 3)));
System.out.println(all);

 

*배열로 옮기기

List<String> list = new ArrayList<>(Arrays.asList("원소", "들을", "여러개"));
String[] arr =  list.toArray(new String[0]);
System.out.println(Arrays.toString(arr)); // [원소, 들을, 여러개]

 

*리스트 자르기

System.out.println(list.subList(1, 3)); // [들을, 여러개]

 

*배열 정렬

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

public class Main9 {
	public static void main(String[] args) {
		List<Integer> list = new ArrayList<>(Arrays.asList(50, 30, 10, 60, 20, 40));
		
		list.sort(new Comparator<Integer>() {
			@Override
			public int compare(Integer o1, Integer o2) {
				return o1 - o2;
			}
		});
		System.out.println(list); // [10, 20, 30, 40, 50, 60]
	}
}

 

*배열 정렬

 

List<Integer> list = new ArrayList<>(Arrays.asList(50, 30, 10, 60, 20, 40));
Collections.sort(list);
System.out.println(list); // [10, 20, 30, 40, 50, 60]

 

*배열 정렬

 

Collections.sort(list, new Comparator<Integer>() {
    @Override
    public int compare(Integer o1, Integer o2) {
        return o1 - o2;
    }
});

 

*이진 검색

int find = Collections.binarySearch(list, 30);
System.out.println(find);

 

*배열 뒤집기

Collections.reverse(list);

 

*원소의 최대, 최소 구하기

int max = Collections.max(list);
int min = Collections.min(list);

 

*셔플

Collections.shuffle(list);

 

*채우기

Collections.fill(list, 99);

 

*원소바꾸기

Collections.replaceAll(list, 10, 99);

 

*원소 지우기

list.remove(list.size() - 1);

 

*comparable 과 equals 차이

equals는 속성의 값들을 비교(동등)

comparable는 속성 값의 크기를 비교(큰지 같은지 작은지)