Last active
August 25, 2022 02:27
-
-
Save HyangKeunChoi/ca1b5a1427a698044ba6dac3401a0464 to your computer and use it in GitHub Desktop.
Comparable & Comparator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ComparableComparatorTest { | |
public static void main(String[] args) { | |
TestClass[] testClass = new TestClass[10]; | |
for (int i = 0; i < 10; i++) { | |
testClass[i] = new TestClass((int)(Math.random()*100)); | |
} | |
// 정렬 전 | |
for(int i = 0; i < 10; i++) { | |
System.out.print(testClass[i].value + " "); | |
} | |
System.out.println(); | |
// comparator로 구현할때는 뒤에 인자로 comparator넘겨줘야 한다. | |
Arrays.sort(testClass, comparator); | |
// 정렬 이후 | |
System.out.print("정렬 후 : "); | |
for(int i = 0; i < 10; i++) { | |
System.out.print(testClass[i].value + " "); | |
} | |
System.out.println(); | |
} | |
// 익명 클래스로 구현 | |
static Comparator comparator = new Comparator<TestClass>() { | |
@Override | |
public int compare(TestClass o1, TestClass o2) { | |
return o2.value - o1.value; | |
} | |
}; | |
} | |
/*class TestClass implements Comparable<TestClass> { | |
int value; | |
public TestClass(int value) { | |
this.value = value; | |
} | |
@Override | |
public int compareTo(TestClass o) { | |
// return this.value - o.value; // 오름차순 | |
return o.value - this.value ; // 바꾸면 내림차순 됨 | |
} | |
}*/ | |
class TestClass { | |
int value; | |
public TestClass(int value) { | |
this.value = value; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment