Collections Framework
Collection(다수의 DATA)을 다루기 위한 표준화된 프로그래밍 방식.
재사용 가능한 컬렉션 데이터 구조를 구현하기 위한 Class 및 Interface의 집합.
Framework라고 표현하나 Library 방식으로 동작한다.
컬렉션 데이터 구조란 범용적으로 사용하는 데이터 구조를 의미한다.
* Collection : 여러 객체(데이터)를 모아 놓은것을 의미.
* Framework : 구현, 실행을 모두 할 수 있는 S/W 환경. 표준화, 정형화된 체계적인 프로그래밍 방식
* Library : 구현, 실행을 위해 사용하는 S/W.
인터페이스 | 특징 | 구현 클래스 | 예 |
List | 순서가 있는 데이터의 집합, 데이터의 중복을 허용한다. | Array List, LinkedList, Stack, Vector | 대기자 명단 |
Set | 순서를 유지 하지 않는 데이터의 집합, 중복을 허용하지 않는다. | HashSet, TreeSet | 소수의 집합 |
Map | key와 value의 쌍으로 이루어진 데이터의 집합, 순서가 유지 되지 않으며 key는 중복을 허용하지 않고 value는 중복을 허용한다. | HashMap, TreeMap, Hashtable, Properties 등 | 우편번호, 지역번호 |
▶ Collection Interface의 Method.
메서드 | 설명 |
boolean add(Object o) boolean addAll(Collection c) |
지정된 객체(o) 또는 Collection(c)의 객체들을 Collectiondp 추가한다. |
void clear() | Collection의 모든 객체를 삭제한다. |
boolean contains(Object o) | 동일한 Collection인지 비교한다. |
int hashCode() | Collection의 hash code를 반환한다. |
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 <E> Interface
순서가 있는 데이터의 집합, 중복허용.
▶ 종류
컬렉션 | 읽기(접근 시간) | 추가 / 삭제 | 비고 |
ArrayList | 빠르다. | 느리다. | 순차적인 추가, 삭제는 더 빠르다.비효율적인 메모리사용. |
LinkedList | 느리다. | 빠르다. | 데이터가 많을수록 접근성이 떨어진다. |
▶ 메서드
메서드 | 설명 |
void add(int index, Object element) boolean addAll(int index, Collection c) |
지정된 위치(index)에 객체(element) 또는 Collection에 포함된 객체들을 추가한다. |
Object get(int index) | 지정된 위치(index)에 있는 객체를 반환한다. |
int indexOf(Object o) | 지정된 객체의 위치를 반환한다. (List의 첫 번째 요소부터 순방향으로 찾는다.) |
int lastIndexOf(Object o) | 지정된 객체의 위치를 반환한다. (List의 마지막 요소부터 역방향으로 찾는다.) |
ListIterator listIterator() ListIterator listIterator(int index) |
List의 객체에 접근 할 수 있는 ListIterator를 반환한다. |
Object remove(int index) | 지정된 위치(index)에 있는 객체를 삭제하고 삭제된 객체를 반환한다. |
Object set(int index, Object element) | 지정된 위치(index)에 객체(element)를 저장한다. |
void sort(Comparator c) | 지정된 비교자(Comparator)로 Listfmf 정렬한다. |
List subList(int fromIndex, int toIndex) | 지정된 범위(fromIndex부터 toIndex)에 있는 객체를 반환한다. |
ArrayList <E>
- 배열 기반 자료구조.
- 저장공간을 늘리는데 시간이
진짜오래걸림. - 삭제 과정의 연산이 오래 걸림.
- 참조가 빠르다.
▶ 배열의 장단점
- 장점
- 구조가 간단하고 데이터를 읽는 데 걸리는 시간(Access time)이 짧다.
- 단점
- 크기를 변경 할 수 없다.
- 크기를 변경할 경우 새로운 배열을 생성 후 데이터를 복사하고 참조해야함.
- 비순차적인 데이터의 추가 도는 삭제의 시간이 많이 걸린다.
- 끝지점의 추가와 삭제는 빠르다.
- 크기를 변경 할 수 없다.
▶ 메서드
메서드 | 설명 |
ArrayList() | 크기가 0인 ArrayList를 생성 |
ArrayList(Collection c) | 주어진 컬렌셕이 저장된 ArrayList를 생성 |
ArrayList(int initialCapacity) | 지정된 초기용량을 갖는 ArrayList를 생성 |
boolean add(Object o) | ArrayList의 마지막에 객체를 추가. 성공하면 true |
void add(int index, Object element) | 지정된 위치(inedx)에 객체를 저장 |
boolean addAll(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를 반환 |
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() | 용량을 크기에 맞춰 줄인다.(빈 공간을 없앤다.) |
public static void main(String[] args) {
// 기본길이(용량, capacity)가 10인 ArrayList를 생성
// ArrayList에는 객체만 저장 가능.
ArrayList list1 = new ArrayList(10);
list1.add(new Integer(1));
list1.add(new Integer(2));
list1.add(new Integer(3));
// autoBoxing에 의해 기본형이 참조형으로 자동 변환
list1.add(4);
list1.add(5);
// ArrayList(Collection c)
ArrayList list2 = new ArrayList(list1.subList(0, 4)); //0~3
print(list1, list2);
//오름 차순 정렬
Collections.sort(list1);
Collections.sort(list2);
// list1에 list2의 모든 요소를 포함하고 있나?
System.out.println("list1.containsAll(list2) = " + list1.containsAll(list2)); // true;
// 추가할 위치를 설정
// 중간위치에 추가하기 때문에 부담이 가는 작업.
list2.add(3, "A");
// 변경
list2.set(3,"AA");
// indexOf()는 지정된 객체의 위치를 알려준다.
System.out.println("index = " + list2.indexOf("AA"));
// 겹치는 부분만 남기고 삭제
System.out.println("list1.retainAll(list2) = " + list1.retainAll(list2));
print(list1, list2);
// list2에서 list1에 포함된 객체들을 삭제.
for(int i = list2.size() - 1; i >= 0; i--){
if(list1.contains(list2.get(0)))
list2.remove(i);
}
// 삭제
list1.remove(0); // 인덱스가 0인걸 삭제
list1.remove(new Integer(2)); //2를 삭제
print(list1, list2);
}
static void print(ArrayList list1, ArrayList list2){
System.out.println("list1 = " + list1);
System.out.println("list2 = " + list2);
}
* Collection은 Interface이고, Collections는 Class임에 주의.
public class ExamCollection {
public static void main(String[] args) {
// Cellection Instance (컬렉션 클래스)의 생성.
// ArrayList 배열은 기반으로 데이터를 유지한다.
// 장점 : 참조는 빠르다, 읽기.
// 단점 : 데이터의 구조가 변하는경우 처리가 느리다.
// 메모리를 잡는게 메모리를 엑세스 하는것보다 몇 만배 느리다 ㅋ.
// 처음부터 Capaacity를 잘 잡아야된다!
// Capacity가 변경되는 순간 끝이다!
// * 데이터의 변경이 없고 읽기가 많은 경우 사용한다.
List<String> list = new ArrayList<>(15000);
// 리스트에 데이터를 입력한다.
list.add("abc");
list.add("kbs");
list.add("JSR");
// 리스트의 데이터를 읽는다.
for(int i = 0; i < list.size(); i++){
System.out.println(list.get(i));
}
System.out.println("--------------------------------------------------------");
// 리스트의 데이터를 지운다.
list.remove(1);
// 리스트의 데이터를 읽는다.
for(int i = 0; i < list.size(); i++){
System.out.println(list.get(i));
}
}
}
LinekedList <E>
- List 기반 자료구조.
- 참조가 느림.
- 데이터 접근성이 나쁨
- 이를 개선한 doubly linked list (실제 java에 구현)
- doubly circular linked list
- 이를 개선한 doubly linked list (실제 java에 구현)
- 데이터 접근성이 나쁨
- 추가, 삭제 등 메모리 할당 해제가 빠름.
- 배열과 달리 불연속적으로 존재하는 데이터를 연결(link)
- 배열의 단점을 보안
- 크기 변경 가능
- 추가 삭제 유리
Iterator (반복자)
- Collection에 저장된 요소들을 읽어오는 방법을 표준화 한것
- 자료구조를 순회 하기 위한 Method
메서드 | 설명 |
boolean hasNext() | 읽어 올 요소가 남아있는지 확인한다. |
Object next() | 다음 요소를 읽어온다. next()를 호출하기 전에 hasNext()를 호출해서 읽어 올 요소가 있는지 확인하는 것이 안전한다. |
▷ 구현
public static void main(String[] args) {
List<String> list = new LinkedList<>();
....
Iterator<String> itr = list.iterator(); ....
while(itr.hasNext()) { // next 메소드가 반환할 대상이 있다면,
str = itr.next(); // next 메소드를 호출한다.
....
}
}
▶ Iterator의 연산
· E next() : 다음 instance의 참조 값을 반환
· boolean hasNext() : next Method 호출 시 참조 값 반환 가능 여부 확인
· void remove() : next method 호출을 통해 반환했던 instance delete
public static void main(String[] args) {
List<String> list = new ArrayList<>(15000);
// 리스트에 데이터를 입력한다.
list.add("abc");
list.add("kbs");
list.add("JSR");
list.add("ZZZ");
Iterator<String> iter = list.iterator();
String temp = null;
while(iter.hasNext()) {
System.out.println(iter.next());
}
System.out.println("-------------------------------------------------------------");
// 삭제
iter = list.iterator();
while(iter.hasNext()) {
// temp에 데이터를 저장
temp = iter.next();
// temp에 데이터가 같다면 remove
if(temp.equals("ZZZ")){
iter.remove();
}
}
System.out.println("-------------------------------------------------------------");
// 다시 출력하기 위해서는 Iterator를 다시 받아 출력.
// 이는 동일한 순환 인터페이스를 제공한다. (list, que...)
iter = list.iterator();
while(iter.hasNext()) {
System.out.println(iter.next());
}
System.out.println("-------------------------------------------------------------");
}
public class sample {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<String>();
// Collection Class를 변경
// HashSet<String> list = new HashSet<String>();
// Set은 Collection의 자손
// Collection의 method만 사용했기 때문에 아래 코드를 검토할 필요 없다.
// 더 유연한 코드
// Collection은 TreeSet과 ArrayList의 조상.
Collection<String> c = new TreeSet<String>();
list.add("1");
list.add("2");
list.add("3");
list.add("4");
list.add("5");
Iterator<String> it = list.iterator();
while(it.hasNext()) {
Object obj = it.next();
System.out.println(obj);
}
while(it.hasNext()) {
Object obj = it.next();
System.out.println(obj);
}
}
}
▶ Map에는 Iterator()가 없다.
keySet(), entrySet(), values()를 호출해서 가져온다.
▷ key가 다른 map 구현
public class mapiter {
public static void main(String[] args) {
Map<String, String> map = new HashMap<String, String>();
map.put("english", "hi");
map.put("korean", "안녕");
Iterator<String> iter = map.keySet().iterator();
while (iter.hasNext()) {
String s = iter.next();
System.out.println(map.get(s));
}
}
}
two-way Iterater (양방향 반복자)
List<E> 를 구현하는 Class만 가질 수 있는 반복자.
메서드 | 설명 |
E Next() | 다음 Instance 참조 값을 반환. |
boolean hasNext() | next method 호출 시 참조 값 반환 가능 여부 확인. |
void remove() | next method 호출을 통해 반환했던 Instance를 삭제. |
E previous() | next method와 기능은 같고 방향만 반대. |
boolean hasPrevious() | hasNext Method와 가능은 같고 방향만 반대 |
void add(E e) | Instance의 추가. |
void set(E e) | Instacned의 변경. |
public static void main(String[] args) {
List <String> list = Arrays.asList("AAA", "BBB", "CCC", "DDD");
// Conversion
list = new ArrayList<String>(list);
// get two-way Iterator.
ListIterator <String> iter = list.listIterator();
// print list =>
String s = null;
System.out.println("=> 방향");
while(iter.hasNext()) {
s = iter.next();
System.out.println(s);
// s가 "AAA"이라면 "AAA2"를 추가한다.
if(s.equals("AAA")){
iter.add("AAA2");
// + tree구조가 아닌 선형 구조라면 넣을 수 있다!
// + list.add(s); 는 에러 발생
}
}
// print list <=
System.out.println("<= 방향");
while(iter.hasPrevious()){
s = iter.previous();
System.out.println(s);
}
System.out.println("-------------------");
// again print.
while(iter.hasNext()) {
s = iter.next();
System.out.println(s);
}
// 기본적으로 안 사용하는게 몸에 좋다. 복잡성 이슈
// 오히려 단방향 두개를 사용하는것이 좋다.
}
Collection Conversion
▶ 배열 대신 ArrayList<E>의 사용
- 장점 : 저장, 삭제가 편리하며 Iterator의 사용이 가능하다.
- 단점 : 선언과 동시에 초기화 하는 코드가 불가능하다.
- 특징 : 메모리구조가 Immutable Instance.
List<String> list = Arrays.asList("Toy", "Robot", "Box");
- 새로운 Instance를 추가할 경우
public ArrayList(Collection<? extends E> c) {
...}
- Collection<E>를 구현한 Collection Instance를 인자로 전달 받는다.
- E는 Instance 생성 과정에서 결저되므로 무엇이든 될 수 있다.
- 매개변수 C로 전달된 Collection Instance에서는 참조만 가능하다.
public static void main(String[] args) {
List<String> list = Arrays.asList("AAA", "BBB", "CCC");
// + 완벽한 Arraylist는 아니다!
// + 용량을 늘이거나 줄이거나 할 수 없다.
// + 편리성 때문에 사용한다.
list = new ArrayList<>(list);
// 새롭게 참조하여 용량의 변경이 가능하다.
list = new LinkedList<>(list);
// LinkedList로도 Conversion이 가능하다!
// 즉 계속해서 Conversion이 가능하다!
list.add("DDD");
for(String s : list) {
System.out.println(s);
}
}
Set <E> Interface
집합과 같은 데이터를 메모리에 저장하고자 할 때 사용되는 자료구조.
저장 순서의 개념이 없다. (저장 순서가 유지 되지 않는다.)
데이터의 중복 저장을 허용하지 않는다.
수학의 "집합" 특징을 가지고 있다.
▷ HashSet
- set Interface를 구현한 대표적인 Collection class
- 순서를 유지하러면 LinkedHashSet Class를 사용.
▷ TreeSet
- 범위 검색과 정렬에 유리한 Collection Class
- HashSet보다 데이터 추가 삭제에 시간이 더 걸림
▶ 메서드
메서드 | 설명 |
boolean add(Object o) boolean addAll(Collection c) |
지정된 객체(o) 또는 Collection(c)의 객체들을 Collection에 추가한다. |
void clear() | Collection의 모든 객체를 삭제한다. |
boolean contains(Object o) boolean containsAll(Collection c) |
지정된 객체(o)또는 Collection의 객체들이 Collection에 포함되어 있는지 확인한다. |
boolean equals(Object o) | 동일한 Collection인지 비교한다. |
int hashCode() | Collection의 hash code를 반환한다. |
boolean remove(Object o) | 지정된 객체를 삭제한다. |
boolean removeAll(Collection c) | 지정된 Colleciton에 포함된 객체들을 삭제한다. |
boolean retainAll(Collection c) | 지정된 Colleciton에 포함된 객체만을 남기고 다른 객체들은 Colleciton에서 삭제한다. 이 작업으로 인해 Colleciton에 변화가 있으면 true를 그렇지 않으면 false를 반환한다. |
int size() | Colleciton에 저장된 객체의 개수를 반환한다. |
Object[] toArray() | Collection에 저장된 객체를 객체배열(Object[])로 반환한다. |
Object[] toArray(Object[] a) | 지정된 배열에 Colleciton의 객체를 저장해서 반환한다. |
▶ 동일 데이터 기준
- Object가 정의 하고 있는 두 method의 호출 결과로 판단
- equals()
- hashCode()
▶ 동일데이터의 판단
- equlas() 와 hashCode()를 Overriding.
- hashCode를 구해서 equals로 비교.
- Mod 연산의 나누는 값이 큰 경우 - Unique
- Mod 연산의 나누는 값이 작은 경우 - 분류
- 분류를 이용하여 연산의 횟수를 줄이기 위해 Equlas(), HashCode()를 Override 한다.
public boolean equals(Object obj) {
if(this == obj)
return true;
if(obj == null)
return false;
if(getClass() != obj.getClass())
return false;
return ((this.model == ((Moniter)obj).model) &&
(this.color == ((Moniter)obj).color));
}
public int hashCode() {
//값이 너무 크기 때문에 작게 해준다.
int hashColor = color.hashCode();
int hashModel = model.hashCode();
return (int)((hashModel + hashColor) / 10000);
}
▶ Hash Algorithm
- 분류 대상 : 3, 5, 7, 12, 25, 31
- 적용 Hash Algorithm : num % 3
* 비둘기 집의 원리 : 42^10의 확률로 충돌 할 수 있다. 비둘기 집의 원리
@Override
public boolean equals(Object obj){
// try를 사용하면 처리 속도의 저하가 발생합니다.
// try{
// if(this.value == ((IntValue)obj).value){
// return true;
// }
// else{
// return false;
// }
// }
// catch(Exception e){
// return false;
// }
if(this == obj)
return true;
if(obj == null)
return false;
if(getClass() != obj.getClass())
return false;
return (this.value == ((IntValue)obj).value);
}
@Override
public int hashCode() {
// return this.value % 3;
return Objects.hash(value);
}
HashSet Interface
- 순서가 유지되지 않으며 중복이 허용되지 않는다.
- 컬렉션 내의 중복 요소들을 쉽게 제거 할 수 있다.
▶ 메서드
생성자 또는 메서드 | 설명 |
HashSet() | HashSet 객체를 생성한다. |
HashSet(Collection c) | 주어진 컬렉션을 포함하는 HashSet객체를 생성한다. |
HashSet(int initailCapacity, float loadFactor) | 초기용량과 load factor를 지정하는 생성자. |
boolean add(Object o) | 새로운 객체를 저장한다. (성공하면 true, 실패하면 false) |
boolean addAll(Collection c) | 주어진 컬렉션에 저장된 모든 객체들을 추가한다.(합집합) |
void clear() | 저장된 모든 객체를 삭제한다. |
Object clone() | HashSet을 복제해서 반환한다. (얕은 복사) |
boolean contains(Object o) | 지정된 객체를 포함하고 있는지 알려준다. |
boolean containsAll(Collection c) | 주어진 컬렉션에 저장된 모든 객체들을 포함하고 있는지 알려준다. |
boolean isEmpty() | HashSet이 비어있는지 알려준다. |
Iterator iterator() | Iterator를 반환한다. |
boolean remove(Object o) | 지정된 객체를 HashSet에서 삭제한다. (성공하면 true. 실패하면 false) |
boolean removeAll(Collection c) | 주어진 컬렉션에 저장된 모든 객체와 동일한 것들을 HashSet에서 모두 삭제한다.(차집합) |
boolean retainAll(Collection c) | 주어진 컬렉션에 저장된 객체와 동일한 것만 남기고 삭제한다. (교집합) |
int size() | 저장된 객체의 개수를 반환한다. |
Object[] toArray() | 저장된 객체들을 객체배열의 형채로 반환한다. |
Object[] toArray(Object[] a) | 저장된 객체들을 주어진 객체배열(a)에 담는다. |
▶ 구현 1
HashSet은 객체를 저장하기 전에 기존에 같은 객체가 있는지 확인한고 같은 객체가 없으면 저장하고, 있으면 저장하지 않는다.
boolean add(Object o)는 저장할 객체의 equals()와 hashCode()를 호출하며 equals()와 hashCode()가 오버라이딩 되어 있어야 한다.
public class ex11_11 {
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);
}
}
// equals(), hashCode()를 오버라이딩 해야 HashSet이 바르게 동작.
class Person {
String name;
int age;
Person(String name, int age) {
this.name = name;
this.age = age;
}
public String toString() {
return name + " : " + age;
}
@Override
public int hashCode() {
// int hash(Object... values) //가변인자
return Objects.hash(name, age); //가변인자 => 변수를 더 넣어도 된다.
}
@Override
public boolean equals(Object o) {
if(!(o instanceof Person))
return false;
// 형변환 필요
Person p = (Person)o;
// this의 이름과 나이를 p로 비교.
return this.name.equals(p.name) && this.age == (p.age);
}
}
▶ 구현 2
public class smple {
public static void main(String[] args) {
Object[] objArr = {"1", new Integer(1), "2", "2", "3", "3", "4", "4"};
Set set = new HashSet();
for(int i = 0; i < objArr.length; i++) {
set.add(objArr[i]); // HashSet에 objArr의 요소들을 저장.
}
// HashSet에 저장된 요소 출력.
System.out.println(set);
// HashSet에 저장된 요소들을 출력한다. (Iterator이용)
Iterator it = set.iterator();
while(it.hasNext()) {
System.out.println(it.next());
}
}
// [1, 1, 2, 3, 4] 1하나는 문자열 객체
// 1
// 1
// 2
// 3
// 4
}
public class smple {
public static void main(String[] args) {
Set set = new HashSet();
// set의 크기가 6이하일 동안 1~45 의 난수저장.
for(int i = 0; set.size() < 6; i++) {
int num = (int)(Math.random() *45) + 1;
set.add(num);
}
// 정렬
// * set은 정렬이 안된다.
// => set의 모든 요소를 list에 저장한뒤 정렬.
List list = new LinkedList(set); //LinkedList(Collection c)
Collections.sort(list); //Collections.sort(List list)
System.out.println(list);
}
}
▶ 구현 3
교집합, 합집합, 차집합 구하기
public class ex11_12 {
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");
System.out.println("A = " + setA);
setB.add("4");
setB.add("5");
setB.add("6");
setB.add("7");
setB.add("8");
System.out.println("B = " + setB);
// 교집합
Iterator it = setB.iterator();
while(it.hasNext()) {
Object tmp = it.next();
if(setA.contains(tmp)) {
setKyo.add(tmp);
}
}
// 차집합
it = setA.iterator();
while(it.hasNext()) {
Object tmp = it.next();
if(!setB.contains(tmp))
setCha.add(tmp);
}
// 합집합
it = setA.iterator();
while(it.hasNext()){
setHab.add(it.next());
}
it = setB.iterator();
while(it.hasNext()) {
setHab.add(it.next());
}
System.out.println("A ∩ B = " + setKyo);
System.out.println("A ∪ B = " + setHab);
System.out.println("A - B =" + setCha);
// 간단하게 구하기
setA.retainAll(setB); // 교집합. 공통된 요소만 남기고 삭제
setA.addAll(setB); // 합집합. setB의 모든 요소를 추가(중복 제외)
setA.removeAll(setB); // 차집합. setB의 공통 요소를 제거
}
}
TreeSet<E> Interface
- 이진 탐색 트리구조(binary search tree)로 구현하여 정렬상태를 유지하면서 저장하는 Interface.
- 이진 트리는 모든 노드가 최대 2개의 하위 노드를 갖는다.
- 정렬상태를 만들기위해 저장되는 Class는 comparable<T> Interface를 Implement 해야한다.
- 별도의 정렬기준을 제시하기 위해 Comparator<T> Interface를 사용.
- 범위 탐색과 정렬에 유리
▶ Binary search tree(이진 탐색 트리)
- 부모보다 작은 값은 왼쪽, 큰값은 오른쪽에 저장.
- 데이터가 많아질 수 록 비교 횟수 증가에 따라 추가 삭제에 더 많은 시간이 소요.
▶ TreeSet의 데이터 저장 과정
- boolean add(Object o)
- 루트부터 트리를 따라 내려가며 값을 비교하여 작으면 왼쪽, 크면 오른쪽에 저장한다.
▶ 주요 생성자 및 메서드
생성자 또는 메서드 | 설명 |
TreeSet() | 기본 생성자 |
TreeSet(Collection c) | 주어진 컬렉션을 저장하는 TreeSet을 생성 |
TreeSet(Comparator comp) | 주어진 정렬기준으로 정렬하는 TreeSet을 생성 |
Object first() | 정렬된 순서에서 첫 번째 객체를 반환한다. |
Object last() | 정렬된 순서에서 마지막 객체를 반환한다. |
Object celling(Object o) | 지정된 객체와 같은 객체를 반환. 없으면 큰 값을 가진 객체 중 제일 가가운 값의 객체를 반환. 없으면 null |
Object floor(Object o) | 지정된 객체와 같은 객체를 반환. 없으면 작은 값을 가진 객체 중 제일 가까운 객체를 반환. 없으면 null |
Object higer(Object o) | 지정된 객체보다 큰 값을 가진 객체 중 제일 가까운 값의 객체를 반환. 없으면 null |
Object lower(Object o) | 지정된 객체보다 작은 값을 가진 객체 중 제일 가까운 값을 객체를 반환. 없으면 null |
SortedSet subSet(Object fromElement, Object toElement) | 범위 검색(fromElement와 toElement사이)의 결과를 반환한다. (끝 범위인 toElement는 범위에 포함되지 않음) |
SortedSet headSet(Object toElement) | 지정된 객체보다 작은 값의 객체들을 반환한다. |
SortedSet tailSet(Object fromElement) | 지정된 객체보다 큰 값의 객체들을 반환한다. |
▶ 범위 검색 메서드
메서드 | 설명 |
SortedSet subSet(Object fromElement, Object toElement) | 범위 검색(fromElement와 toElement사이)의 결과를 반환한다. (끝 범위인 toElement는 범위에 포함되지 않는다.) |
SortedSet headSet(Object toElement) | 지정된 객체보다 작은 값의 객체들을 반환한다. |
SortedSet tailSet(Object fromElement) | 지정된 객체보다 큰 값의 객체들을 반환한다. |
public static void main(String[] args) {
// tree set
TreeSet<Integer> tree = new TreeSet<>();
// input the data
tree.add(1);
tree.add(2);
tree.add(7);
tree.add(3);
tree.add(9);
// size 출력
System.out.println("count = " + tree.size());
// print of for
for(Integer i : tree){
System.out.println(i);
}
System.out.println("--------------------------------------------------------");
// print of iterator
Iterator<Integer> iter = tree.iterator();
while(iter.hasNext()){
System.out.println(iter.next());
}
}
▶구현 1
TreeSet은 저장할 때 이미 정렬하기 때문에 읽어올 때 따로 정렬할 필요가 없다.
public class smple{
public static void main(String[] args) {
Set set = new TreeSet(); // 범위 검색, 자동 정렬됨.
for (int i = 0; set.size() < 6; i++) {
int num = (int)(Math.random() *45) +1;
set.add(num); // set.add(new Integer(num))
}
System.out.println(set);
}
}
▶구현 2
TreeSet은 범위를 검색할 때 유리하다.
subSet을 이용하여 b~d의 문자만을 추출한다.
public class ex11_14 {
public static void main(String[] args) {
TreeSet set = new TreeSet();
String from = "b";
String to = "d";
set.add("abc"); set.add("car"); set.add("dance");
set.add("elephant"); set.add("flower"); set.add("alien");
set.add("Car"); set.add("dZZZZ"); set.add("elevator");
set.add("bat"); set.add("dzzzz");
System.out.println(set);
System.out.println("range serch : from " + from + " to " + to);
System.out.println("result1 : " + set.subSet(from, to)); // 전체 집합중 부분집합만 추출
System.out.println("result2 : " + set.subSet(from, "dzzz"));
}
}
▶구현 3
public class ex11_15 {
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(new Integer(score[i]));
}
System.out.println("50보다 작은 값 : " + set.headSet(new Integer(50)));
System.out.println("50보다 큰 값 : " + set.tailSet(50));
System.out.println("40과 80사이의 값 : " + set.subSet(40, 80));
}
}
}
* Tree traversal(트리 순회)
- 이진 트리의 모든 노드를 한번씩 읽는 것을 트리 순회 라고 한다.
- 전위, 중위, 후위 순회법이 있으며, 중위 순회하면 오름차순으로 정렬된다.
Comparator & Comparable
객제 정렬에 필요한 method(정렬기준 제공)를 정의한 Interface.
compare()와 comparTo()는 두 객체의 비교결과를 반환하도록 작성.
Comparable | 기본 정렬기준을 구현하는데 사용. |
Comparator | 기본 정렬기준 외에 다른 기준으로 정렬하고자 할 때 사용. |
* 정렬 sort() - 두 대상을 비교한 후 자리를 바꾸는 로직을 반복한다.
▶ 구현
Arrays.sort로 String[]을 정렬하는 예제.
String class 내부에 Comparable이 구현되어 있다.
public class smple {
public static void main(String[] args) {
String[] strArr = {"cat", "Dog", "lion", "tiger"};
Arrays.sort(strArr); // (strArr, 정렬기준)으로 해야하지만 String 자체의 Comparable 구현에 의한 정렬
System.out.println("strArr = " + Arrays.toString(strArr));
Arrays.sort(strArr, String.CASE_INSENSITIVE_ORDER); //대소문자 구분안함.
System.out.println("strArr = " + Arrays.toString(strArr));
Arrays.sort(strArr, new Descending()); //역순 정렬
System.out.println("strArr = " + Arrays.toString(strArr));
}
}
class Descending implements Comparator {
public int compare(Object o1, Object o2) {
if (o1 instanceof Comparable && o2 instanceof Comparable) {
Comparable c1 = (Comparable)o1;
Comparable c2 = (Comparable)o2;
return c1.compareTo(c2) * -1; // -1을 곱해서 기본 정렬방식의 역으로 변경.
// 또는 c2.compareTo() 와 같이 순서를 바꿔도된다.
}
return -1;
}
}
Comparator<T> Interface
정렬기준을 바꾸고 싶은 경우 아래와 같이 처리한다.
public static void main(String[] args) {
TreeSet<Person> pSet = new TreeSet<Person>(new PersonComparator());
}
}
public class PersonComparator implements Comparator<Person> {
public int compare(Person p1, Person p2){
return p2.getName().length() - p1.getName().length();
}
}
public static void main(String[] args) {
TreeSet<Person> pSet = new TreeSet<Person>(new PersonComparator());
}
public int compare(Person p1, Person p2){
return p2.getName().length() - p1.getName().length();
}
compareTo()
단순한 정렬이 아닌 사용자가 정의한 기준에 따라 정렬한다.
public static void main(String[] args) {
TreeSet<Person> pSet = new TreeSet<Person>();
pSet.add(new Person("John", 11));
pSet.add(new Person("Sam", 54));
pSet.add(new Person("chan", 25));
pSet.add(new Person("Koo", 15));
Iterator<Person> iter = pSet.iterator();
while(iter.hasNext()) {
System.out.println(iter.next());
}
@Override
public int compareTo(Person other) {
//return this.age - other.age 오름차순
//return other.age - this.age 내림차순
// 나이를 기준으로 정렬
if(this.age > other.age){
return 1;
}
else if(this.age < other.age){
return -1;
}
else{ //같은 경우
return 0;
}
}
Stack Class,
Queue<E> Interface
Stack | LIFO 구조 | ArrayList로 만드는데 적합 |
Queue | FIFO 구조 | LinkedList로 만드는데 적합 |
스택 활용의 예
- 수식계산, 수식괄호검사, 워드프로세서의 undo/redo, 웹브라우저의 뒤로/앞으로
큐의 활용 예
- 최근 사용 문서, 인쇄작업 대기목록, 버퍼(buffer)
▶ Stack 메서드
메서드 | 설명 |
boolean empty() | Stack이 비어있는지 알려준다. |
Object peek() | Stack의 맨 위에 저장된 객체를 반환. pop()과 달리 Stack에서 객체를 꺼내지는 않음(비었을 때 EmptyStackException 발생) |
Object pop() | Stack의 맨 위의 저장된 객체를 꺼낸다. (비었을 때는 EmptyStackException 발생) |
Object push(Object item) | Stack에 객체(item)을 저장한다. |
int search(Object o) | Stack에 주어진 객체(o)를 찾아서 그 위치를 반환. 못 찾으면 -1을 반환. (배열과 달리 위치는 0이 아닌 1부터 시작. 맨위의 요소가 1) |
▶ Queue 메서드
메서드 | 설명 |
boolean add(Object o) | 지정된 객체를 Queue에 추가한다. 성공하면 true를 반환. 저장공간이 부족하면 IllergalStateException 발생 |
Object remove() | Queue에서 객체를 꺼내 반환. 비어있으면 NoSuchElementException 발생 |
Object element() | 삭젱벗이 요소를 읽어온다. peek와 달리 Queue가 비었을 때 NoSuchElementException발생 |
boolean offer(Object o) | Queue에 객체를 저장. 성공하면 true. 실패하면 false를 반환 |
Object poll() | Queue에서 객체를 꺼내서 반환, 비어 있으면 null을 반환 |
Object peek() | 삭제없이 요소를 읽어 온다. Queue가 비어 있으면 null을 반환. |
* Queue는 메모리가 부족하면 예외를 발생시킨다.
Queue Method
- 예외 발생
- add()
- remove()
- element()
- 예외 미발생
- offer()
- poll()
- peek()
▶ 간단한 Stack & Queue 구현
public static void main(String[] args) {
Queue q = new LinkedList(); //Q인터페이스의 구현
Stack st = new Stack();
st.push("0");
st.push("1");
st.push("2");
q.offer("0");
q.offer("1");
q.offer("2");
System.out.println("=Stack=");
while(!st.isEmpty()){
System.out.println(st.pop()); // Stack에서 요소 하나를 꺼내
}
System.out.println("=Queue");
while(!q.isEmpty()){
System.out.println(q.poll()); // Queue에서 요소 하나를 꺼내
}
}
▶ Stack의 활용 예제
public class sample {
public static void main(String[] args) {
Stack st = new Stack();
String expression = "((3+5*8-2))";
try{
for (int i = 0; i < expression.length(); i++) {
char ch = expression.charAt(i); // i인덱스의 문자 추출
if (ch == '('){
st.push(ch + "");
}
else if (ch == ')'){
st.pop();
}
}
if (st.isEmpty()) {
System.out.println("괄호가 일치합니다.");
}
else{
System.out.println("괄호가 일치하지 않습니다.");
}
}
catch (Exception e) {
System.out.println("Error 괄호가 일치하지 않습니다.");
}
}
}
▶ Queue의 활용 예제1
public static void main(String[] args) {
// queue는 interface, 기능 집합이다.
// queue를 가지고 linkedList를 구현하겠다.
// queue를 가지고 ArrayList는 구현 되지 않는다.
Queue<String> q = new LinkedList<String>();
String temp;
// offer와 add는 같다.
q.offer("data1");
q.offer("data2");
q.offer("data3");
temp = q.peek();
System.out.println("peek() : " + temp);
temp = q.poll();
System.out.println("poll() : " + temp);
temp = q.poll();
System.out.println("poll() : " + temp);
temp = q.poll();
System.out.println("poll() : " + temp);
temp = q.poll();
System.out.println("poll() : " + temp); //null
// Exception Code
// remove
try{
temp = q.remove();
}
catch (Exception e){
System.out.println("remove() : " + temp);
}
// element
try{
temp = q.element();
}
catch (Exception e){
System.out.println("element() : " + temp);
}
}
▶ Queue의 활용 예제2
public class sample {
static Queue q = new LinkedList();
static final int MAX_SIZE = 5;
public static void main(String[] args) {
System.out.println("help를 입력하면 도움말을 볼 수 있습니다.");
while(true){
System.out.print(">>");
try{
// 화면으로부터 라인단위로 입력받는다.
Scanner s = new Scanner(System.in);
String input = s.nextLine().trim(); //trim() : 양쪽 끝의 공백 제거
if("".equals(input))
continue;
if(input.equalsIgnoreCase("q")) // equalsIgnoreCase() : 문자열을 대소문자 상관없이 비교
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의 내용을 보여준다.
LinkedList list = (LinkedList)q;
final int SIZE = list.size();
for(int i = 0; i < SIZE; i++){
System.out.println((i+1) + "." + list.get(i));
}
}
else{
save(input);
System.out.println(input);
}
}
catch(Exception e){
System.out.println("입력오류입니다.");
}
}
}
public static void save(String input){
// queue에 저장한다.
if(!"".equals(input)){
q.offer(input); // Queue에 객체를 저장
}
if(q.size() > MAX_SIZE){
q.remove(); // Queue에 객체를 꺼내 반환.
}
}
}
Map<K, V> Interface
- Map<K, V> Interface
- K : Key, data의 식별자
- V : Value, 실제 data
- 즉 Key - Value의 쌍으로 data를 유지하기 위한 Interface
- iterable을 상속하지 않음.
- Iterator를 사용하지 못함
▶ HashMap<K, V>
- Map Interface를 구현한 대표적인 Collection Class
- Hash Algorithm 기반의 분류기능을 가진 Map구조.
- 분류
Unique : 보안에서 사용
▶ LinkedHashMap
- 순서가 있다.
▶ TreeMap <K, V>
- 범위 검색, 정렬에 유리한 Colleciton class
- 이진탐색트리 구조
- HashMap보다 데이터 추가, 삭제에 시간이 더 걸림
▶ 메서드
메서드 | 설명 |
void clear() | Map의 모든 객체를 삭제한다. |
boolean containsKey(Object key) | 지정된 key객체와 일치하는 Map의 key객체가 있는지 확인한다. |
boolean containsValue(Object value) | 지정된 value객체와 일치하는 Map의 Value객체가 있는지 확인한다. |
Set entrySet() | Map에 저장되어 있는 key-value쌍을 Map.Entry 타입의 객체로 저장한 set으로 반환한다. |
boolean equals(Object o) | 동일한 Map인지 비교한다. |
Object get(Object key) | 지정한 key객체에 대응하는 value객체를 찾아서 반환한다. |
int hashCode() | 해시코드를 반환한다. |
boolean isEmpty() | Map이 비어 있는지 확인한다. |
Set keySet() | Map에 저장된 모든 key객체를 반환한다. |
Object put(Object key, Object Value) | Map에 value객체를 key객체에 연결(mapping)하여 저장한다. |
void putAll(Map t) | 지정된 Map의 모든 key-value쌍을 추가한다. |
Object remove(Object key) | 지정한 key객체와 일치하는 key-value객체를 삭제한다. |
int size() | Map에 저장된 key-value쌍의 개수를 반환한다. |
Collection values() | Map에 저장된 모든 value 객체를 반환한다. |
HashMap
- Hashing(해싱) 기법으로 데이터를 저장.
- 데이터가 많아도 검색이 빠르다.
- Map Interface를 구현.
- 데이터를 key, value의 쌍으로 저장.
key | Collection내의 key중에서 유일해야한다. |
value | key와 달리 데이터의 중복을 허용한다. |
▶ Hashing
hash function로 hash table에 데이터를 저장하고 검색한다.
- 키로 해시함수를 호출해서 해시코드를 얻는다.
- 해시코드(해시함수의 반환값)에 대응하는 링크드리스트를 배열에서 찾는다.
- 링크드리스트에서 키와 일치하는 데이터를 찾는다.
※ 해시함수는 같은 키에 대해 항상 같은 해시코드를 반환해야한다. 서로 다른 키일지라도 같은 값의 해시코드를 반환 할 수 도 있다.
* hash table은 배열과 linked list가 조합된 상태
- 접근성, 변경이 유리
▶ 메서드
생성자 / 메서드 | 설명 |
HashMap() | HashMap() 객체를 생성 |
HashMap(int initialCapacity) | 지정된 값을 초기용량으로 하는 HashMap객체를 생성 |
HashMap(int initialCapacity, float loadFactor) | 지정된 Map의 모든 요소를 포함하는 HashMap을 생성 |
HashMap(Map m) | 지정된 Map의 모든 요소를 포함하는 HashMap을 생성 |
void clear() | HashMap에 저장된 모든 객체를 제거 |
Object clone() | 현재 HashMap을 복제해서 반환 |
boolean containsKey(Object key) | HashMap에 지정된 키가 포함되어 있는지 알려준다. (포함되어 있으면 true) |
boolean containsValue(Object value) | HashMap에 지정된 값(value)가 포함되어 있는지 알려준다. |
Set entrySet() | HashMap에 저장된 키와 값을 엔트리(키와 값의 결합)의 형태로 Set에 저장해서 반환 |
Object get(Object key) | 지정된 key의 값을 반환, 못찾으면 null 반환 |
Object getOrDefault(Object key, Object defaultValue) | 지정된 key의 값(객체)을 반환한다. 키를 못찾으면 기본값(defaultvalue)으로 지정된 객체를 반환. |
boolean isEmpty() | HashMap이 비어있는지 알려준다. |
Set keySet() | HashMap에 저장된 모든 키가 저장된 Set을 반환. |
Object put(Object key, Object value) | 지정된 키와 값을 HashMap에 저장 |
void putAll(Map m) | Map에 저장된 모든 요소를 HashMap에 저장 |
Object remove(Object key) | HashMap에서 지정된 키로 저장된 값(객체)을 제거 |
Object replace(Object key, Object value) | 지정된 키의 값을 지정된 객체(value)로 대체 |
boolean replace(Object key, Object oldValue, Object newValue) | 지정된 키와 객체(oldValue)가 모두 일치하는 경우에만 새로운 객체(newValue)로 대체 |
int size() | HashMap에 저장된 요소의 개수로 반환 |
Collection values() | HashMap에 저장된 모든 값을 Collection의 형태로 반환 |
▶ 구현 1
id, pwd를 입력받는다.
public class smple {
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("id와 psw를 입력하세요.");
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("입력하신 id는 존재하지 않습니다. 다시 입력하세요.");
continue;
}
if(!(map.get(id)).equals(password)){
System.out.println("비밀번호가 일치하지 않습니다. 다시 입력하세요");
}
else{
System.out.println("id와 비밀번호가 일치합니다.");
break;
}
}
}
}
▶ 구현 2
총점, 평균, 최저 최고점을 구한다.
public class smple {
public static void main(String[] args) {
HashMap map= new HashMap();
map.put("김자바", new Integer(90));
map.put("김자바", 100);
map.put("이자바", 100);
map.put("강자바", 80);
map.put("안자바", 90);
Set set = map.entrySet();
Iterator it = set.iterator();
while(it.hasNext()) {
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));
}
}
▶ 구현 3
텍스트의 단어 빈도수를 계산한다.
public class ex11_18 {
public static void main(String[] args) {
String[] data = {"A", "K", "A", "K", "D", "K", "A", "K", "K", "K", "Z", "D"};
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 e = (Map.Entry)it.next();
int value = (int)e.getValue();
System.out.println(e.getKey() + " : " + printBar('#', value) + " " + value);
}
}
private static Object printBar(char c, int value) {
char[] bar = new char[value];
for(int i = 0; i < bar.length; i++) {
bar[i] = c;
}
return new String(bar);
}
}
▶ 구현 4
public static void main(String[] args) {
HashMap<Integer, String> map = new HashMap<Integer, String>();
// key와 value를 연결해서 넣어줌
map.put(1, "abc");
map.put(2, "def");
map.put(3, "ksb");
map.put(4, "abc");
map.put(5, "def");
Set<Integer> kSet = map.keySet();
for(Integer n : kSet){
System.out.println(map.get(n));
}
System.out.println("-------------------");
Iterator<Integer> iter = kSet.iterator();
while(iter.hasNext()){
Integer i = iter.next();
System.out.println(i + ":" + map.get(i));
}
System.out.println("-------------------");
// print the data of map
System.out.println(map.get(1));
System.out.println(map.get(2));
System.out.println(map.get(3));
System.out.println("-------------------");
// delete the data of map
map.remove(1);
System.out.println(map.get(1)); //null
System.out.println(map.size()); //2
}
▶ Person Class
public static void main(String[] args) {
HashMap<Integer, Person> map = new HashMap<Integer, Person>();
map.put(1, new Person("John", 19));
map.put(2, new Person("Sam", 34));
map.put(3, new Person("K", 27));
map.put(4, new Person("V", 25));
map.put(5, new Person("Owen", 33));
Set<Integer> kSet = map.keySet();
Iterator<Integer> iter = kSet.iterator();
while (iter.hasNext()) {
Integer i = iter.next();
System.out.println(i + " : " + map.get(i));
}
}
public class Person implements Comparable<Person> {
// 단순한 정렬이 아닌 기준이 존재하는 정렬을 생성한다.
private String name;
private int age;
Person(){
this("none", 0);
}
Person(String name, int age) {
this.name = name;
this.age = age;
}
// getter
public int getAge() {
return this.age;
}
public String getName() {
return this.name;
}
@Override
public int compareTo(Person other) {
// 이름의 글자수 기준, 오름차순
if(this.name.length() > other.name.length()){
return 1;
}
else if(this.name.length() < other.name.length()){
return -1;
}
else{ //같은 경우
return 0;
}
}
@Override
public String toString(){
return "Person[name : " + name + ", age : " + age + "]";
}
}
'JAVA' 카테고리의 다른 글
[Java] Format Class(형식화 클래스) (0) | 2022.07.15 |
---|---|
[Java] Calendar Class (0) | 2022.07.14 |
[Java] Method of Math (0) | 2022.06.29 |
[Java] String Class의 Constructor & Method (0) | 2022.06.22 |
[Java] Object Class, Wrapper Class, Arrays Class (0) | 2022.06.22 |