Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- servlet프로젝트
- 코틀린기초
- Google Place Photo API
- DynamicWebProject
- tomcat설정
- ObjectCalisthenics
- java
- jsp프로젝트
- 트랜잭션
- 테코톡
- 트랜잭션속성
- 자바비동기
- 코틀린뽀개기
- GithubOAuth
- 객체지향생활체조
- 리버스프록시
- 무중단배포
- 코틀린
- KotlinInAction
- 스프링트랜잭션
- S2139
- kotlin
- 레벨로그
- 우아한테크코스
- 백준
- 트랜잭션성질
- subprocess에러
- mysqld.sock
- 알고리즘
- 데이터베이스락
Archives
- Today
- Total
초이로그
Java 비교정렬(Comparable vs. Comparator) 본문
보통 배열 → Arrays.toString(arr)로 출력
linkedList, arrayList, map, set 자료구조의 경우 그냥 print문으로 넣어서 확인 가능
정렬기준을 만들어야하는 경우 무조건 comparable 또는 comparator를 이용해야함
Comparator
정렬 기준이 자주 바뀌는 경우에 사용. 양팔저울 느낌
알고리즘에서는 추천하지 않음
'new Comparator<객체>' 로 비교 기준 생성
기본(Int)형 비교:
Collections.sort(students, new Comparator(<Student>(){
@Override
public int compare(Studnet o1, Studnet 02){
return o1.score - o2.score;
}
};
오름차순 -> 첫번째를 기준
내림 차순 -> 두번째를 먼저 쓰기 (o2.score - o1.score);
double형 비교(실수 비교):
Collections.sort(students, new Comparator(<Student>(){
@Override
public int compare(Studnet o1, Studnet 02){
if (o1.score > o2.score)
return 1;
else if(o1.score < o2.score)
return -1;
else
return 0;
}
};
compare함수의 리턴타입이 Int형이라서 단순히 뺄셈 연산으로 리턴 X.
소수점이 나올 수 있으므로 comparator의 정석적인 방법(리턴 -1, 1, 0)으로 구현
String 비교(람다식 사용ver.)
Collections.sort(students, (o1, o2) -> {
return o1.name.compareTo(o2.name);
});
compareTo에서 String비교 가능함을 이용
Comparable
항상 일정한 기준으로 정렬.
알고리즘 문제 풀 때 추천
객체 자체를 비교가능하게 만들어서 정렬
예제:
ArrayList<Product> foods = new ArrayList<>();
class Product implements Comparable<Product>{
String name;
String maker;
int price;
public Product(String name, String maker, int price){
//생성자
}
// Product 내부에서 비교할수 있는 함수 구현
@Override
public int compareTo(Product o) {
return this.price - o.price;
}
}
위처럼 객체가 Comparable을 implements 하여 compareTo함수를 구현
Collections.sort(foods);
이렇게 .sort로 정렬 실행
정렬 기준 2개:
class Product implements Comparable<Product>{
// ...
@Override
public int compareTo(Product o) {
//가격이 같은 경우 이름으로 정렬
if(this.price - o.price){
return this.name.compareTo(o.name);
}
return this.price - o.price;
}
}
'Programming Language > Java' 카테고리의 다른 글
[Effective JAVA 3/E] 9장. 일반적인 프로그래밍 원칙 (0) | 2021.08.12 |
---|---|
[Intellij] Servlet 프로젝트 생성하기(JSP, Web Dynamic Project 생성하기) (15) | 2021.04.09 |