Collection(컬렉션)에 대해서
계기 ?
회사에서 백엔드 코드를 살펴보다가 List를 Stream으로 변환해서 안의 내용을 가공한 다음,
collect 함수를 이용해서 다시 List로 만들어주는 내용을 접했다.
이 코드로 List, Map, Set 그리고 Collections에 대해서 정확히 알아보고 싶어졌다.
내용
구글에 다른 개발자들의 설명을 보기 전에, 가장 기본이 되는 Java Doc에 정의된 내용을 살펴봤다.
https://docs.oracle.com/javase/8/docs/api/index.html
Class Collections
java.util.Collections
public class Collections
extends Object
The methods of this class all throw a NullPointerException if the collections or class objects provided to them are null.
The documentation for the polymorphic algorithms contained in this class generally includes a brief description of the implementation. Such descriptions should be regarded as implementation notes, rather than parts of the specification. Implementors should feel free to substitute other algorithms, so long as the specification itself is adhered to. (For example, the algorithm used by sort does not have to be a mergesort, but it does have to be stable.)
The "destructive" algorithms contained in this class, that is, the algorithms that modify the collection on which they operate, are specified to throw UnsupportedOperationException if the collection does not support the appropriate mutation primitive(s), such as the set method. These algorithms may, but are not required to, throw this exception if an invocation would have no effect on the collection. For example, invoking the sort method on an unmodifiable list that is already sorted may or may not throw UnsupportedOperationException.
This class is a member of the Java Collections Framework.
위 내용을 나름 요약해보자면,
Collections 클래스는 컬렉션 안에서 작업하거나 반환하는 정적인 메소드들로 구성되어 있고,
클래스 안에 메소드가 없으면 (즉, 객체가 null이라면) NullPointerException을 던진다.
이렇게 공식 문서에 정의된 내용만 가지고는 와닿는게 없어서 구글에 더 검색을 해봤다.
아래의 그림은 Collection에 대해서 이해하는데 도움이 되어서 가져와봤다.
그림만 살펴보면 Collection에 구성된 것은 List, Set이라고만 볼 수 있는데, Map도 포함된다.
간단하게 List, Set, Map의 특징을 살펴보자.
인터페이스 | 구현클래스 | 특징 |
Set | HashSet TreeSet |
순서를 유지하지 않는 데이터의 집합으로 데이터의 중복을 허용하지 않는다. |
List | LinkedList Vector ArrayList |
순서가 있는 데이터의 집합으로 데이터의 중복을 허용한다. |
Queue | LinkedList PriorityQueue |
List와 유사하다. |
Map | Hashtable HashMap TreeMap |
키(Key), 값(Value)의 쌍으로 이루어진 데이터의 집합으로, 순서는 유지되지 않으며 키(Key)의 중복을 허용하지 않으나 값(Value)의 중복은 허용한다. |
위의 표는 https://gangnam-americano.tistory.com/41 에서 가져왔다.
각 인터페이스에 구현된 클래스들에 대한 내용과 특징은 집에 있는 자바 책을 다시 살펴보고 정리해봐야겠다.