728x90
반응형
Class Case Exception
import java.util.Arrays;
class Burger{
String name;
int price;
Burger(String name, int price){}
}
public class Test01 {
public static void main(String[] args) {
Burger[] burgers = new Burger[3];
burgers[0] = new Burger("1957",6000);
burgers[1] = new Burger("더블불고기",7000);
burgers[2] = new Burger("한우버거", 8000);
Arrays.sort(burgers); //Exception occurs
}
}
위 코드를 실행 시키면 ClassCaseException이 발생한다
이는 Arrays.sort의 기준점인 comparable에 버거 객체 (name,int)를 정렬하는 기준점이 없기 때문이다. 이를 해결하기 위해서는 comparable class를 implements 해서 compareTo 메서드를 오버라이딩 해줘야한다.
🤦🏻♀️ CompareTo Method
return values: 음수, 0 , 양수
음수값 리턴: 내가 비교대상보다 앞에 있다
0 리턴: 비교 대상과 자리를 바꾸지 않겠다 (이동 x)
양수값 리턴: 내가 비교대상보다 뒤에 있다
CompareTo를 활용
public class Student implements Comparable<Student>{
int no, score;
public int getNo() {return this.no;}
public void setNo(int no) {this.no = no;}
public int getScore() {return this.score;}
public void setScore(int score) {this.score = score;}
@Override
public String toString() {
return "Student [no=" + no + ", score=" + score + "]";
}
/* 음수값이 리턴일 경우 기준점이 비교대상의 앞에 위치
* 양수값이 리턴일 경우 기준점이 비교대상의 뒤의 위치
* 0일 경우 이동 없음*/
@Override
public int compareTo(Student o) {
return this.no - o.no; //오름차순
}
CompareTo
1. 내 번호(this.no): 7번
2. 비교 대상 번호(o.no): 3번 //o는 파라미터 안에 들어간 객체임
→ this.no - o.no >0. 양수니까 내가 비교 대상보다 뒤에 있음→이동
1. 내번호(this.no):3번
2. 비교 대상 번호(o.no): 7번 → this.no - o.no <0 : 음수니까 앞으로 이동
🤦🏻♀️ 내림차순으로 정렬하고 싶다면 return값을 o.no - this.no; 로 주면 된다
테스트 해보면,
import java.util.Arrays;
public class Test02 {
public static void main(String[] args) {
Student[] arr = {
new Student(2,14),
new Student(1,50),
new Student(4,35),
new Student(3, 90)
};
System.out.println(Arrays.toString(arr));
Arrays.sort(arr);//CompareTo를 오버라이드해서 가능
System.out.println(Arrays.toString(arr));
}
}
Sort 가 안되어있는 출력값:
[Student [no=2, score=14], Student [no=1, score=50], Student [no=4, score=35], Student [no=3, score=90]]
오버라이딩된 Sort를 이용한 출력값:
[Student [no=1, score=50], Student [no=2, score=14], Student [no=3, score=90], Student [no=4, score=35]]
Comparable 인터페이스 활용
Comparator 인터페이스 구현
private static class StudentComparator implements Comparator <Student>{
@Override
public int compare(Student o1, Student o2) {
return o2.no - o1.no; //내림차순
}
}
//점수 순으로 오름차순, 점수가 같으면 번호로 내림차순으로 기준을
//한가지 이상으로 둘 때:
private static class StudentComparator2 implements Comparator <Student>{
@Override
public int compare(Student o1, Student o2) {
if(o2.score==o1.score) return o2.no-o1.no;//내림차순
else return o1.score - o2.score ; //오름차순
}
}
메인 메서드:
public static void main(String[] args) {
Student[] arr = {
new Student(2,14),
new Student(1,50),
new Student(4,35),
new Student(5,50), //점수가 같을 때
new Student(3, 90)
};
// Student Comparator가 정렬의 기준이 된다
// Arrays.sort(arr, new StudentComparator1());
// System.out.println(Arrays.toString(arr));
Arrays.sort(arr, new StudentComparator2());
System.out.println(Arrays.toString(arr));
}
익명 클래스 이용
private 클래스가 아닌 익명 클래스로 만들때에는 new 키워드 다음에는 상속 클래스가 와야한다
Arrays.sort(arr, new Comparator<Student>(){
@Override
public int compare(Student o1, Student o2){
return o1.score-o2.score;
}
});
System.out.println(Arrays.toString(arr));
람다식 이용
🤦🏻♀️ @FunctionalInterface: 인터페이스 안에 메서드가 하나만 있는 경우 → 람다와 연관지어서 생각하자
- 람다 클래스에서 인터페이스의 선언문 빼고(하나밖에 없어서) 메서드 이름을 쓸 필요가 없다.
- 반환 타입 역시 인터페이스가 있기 때문에 필요 없다.
- 또한, Student 역시 추론이 가능하다 (arr배열에 이미 Student 가 들어가 있어서 → Student 타입도 빠져도 된다)
- 한문장 일 때, 중괄호 생략 가능하지만, 리턴을 반드시 제거해야함
Arrays.sort(arr, (o1, o1)-> o1.score - o2.score);
System.out.println(Arrays.toString(arr));
728x90
반응형
'취준 > JAVA' 카테고리의 다른 글
추상화 (0) | 2022.05.17 |
---|---|
객체 지향 프로그래밍 (0) | 2022.05.17 |
JAVA Basics (0) | 2022.05.12 |
Variables (0) | 2021.07.15 |
다짐 (0) | 2021.07.15 |