comparator

  • interface

  • Comparable์„ ๊ตฌํ˜„ํ•˜๋ฉด ๊ธฐ๋ณธ์ ์œผ๋กœ ์˜ค๋ฆ„์ฐจ์ˆœ ์ •๋ ฌ์ธ๋ฐ, ์ด์™€ ๋‹ค๋ฅด๊ฒŒ ์‚ฌ์šฉํ•˜๊ณ  ์‹ถ์„ ๋•Œ ์‚ฌ์šฉํ•œ๋‹ค?

    • ์ต๋ช…ํด๋ž˜์Šค๋กœ ๋งŽ์ด ์ด์šฉ๋จ.

์–ด๋–ป๊ฒŒ ๊ตฌํ˜„ํ•˜๋Š”๊ฐ€?

  • compare() ๋ฉ”์„œ๋“œ๋ฅผ ์˜ค๋ฒ„๋ผ์ด๋“œ ํ•œ๋‹ค! - ํŒŒ๋ผ๋ฏธํ„ฐ๋ผ๋ฆฌ ๋น„๊ตํ•˜๋Š” ์ปจ์…‰

    • ์ฒซ๋ฒˆ์งธ ํŒŒ๋ผ๋ฏธํ„ฐ ๊ฐ์ฒด < ๋‘๋ฒˆ์จฐ ํŒŒ๋ผ๋ฏธํ„ฐ ๊ฐ์ฒด : ์Œ์ˆ˜ ๋ฆฌํ„ด --> ์ž๋ฆฌ ์•ˆ ๋ฐ”๋€œ

    • ์ฒซ๋ฒˆ์งธ ํŒŒ๋ผ๋ฏธํ„ฐ ๊ฐ์ฒด == ๋‘๋ฒˆ์งธ ํŒŒ๋ผ๋ฏธํ„ฐ ๊ฐ์ฒด : 0 ๋ฆฌํ„ด --> ์ž๋ฆฌ ์•ˆ๋ฐ”๋€œ

    • ์ฒซ๋ฒˆ์งธ ํŒŒ๋ผ๋ฏธํ„ฐ ๊ฐ์ฒด > ๋‘๋ฒˆ์จฐ ํŒŒ๋ผ๋ฏธํ„ฐ ๊ฐ์ฒด : ์–‘์ˆ˜ ๋ฆฌํ„ด --> ์ž๋ฆฌ ๋ฐ”๋€œ

์‚ฌ์šฉ๋ฐฉ๋ฒ•์€?

  • Arrays.sort(arry, myComparator)

  • Collections.sort(list, myComparator)

ํŠน์ดํ•œ ๋ถ€๋ถ„

  • PriorityQueue ์ƒ์„ฑ์ž ๋‘๋ฒˆ์งธ ์ธ์ž๋กœ Comparator ๋ฅผ ๋ฐ›์„ ์ˆ˜ ์žˆ์Œ!

  • ์ฆ‰ ์šฐ์„ ์ˆœ์œ„ ๊ธฐ์ค€์„ ์ •ํ•ด์ค„ ์ˆ˜ ์žˆ๋”ฐ


์˜ˆ์‹œ ์ฝ”๋“œ

class MyComparator implements Comparator<Point> {
 @Override
 public int compare(Point p1, Point p2) {
   if (p1.x > p2.x) {
     return 1; // x์— ๋Œ€ํ•ด์„œ๋Š” ์˜ค๋ฆ„์ฐจ์ˆœ
   }
   else if (p1.x == p2.x) {
     if (p1.y < p2.y) { // y์— ๋Œ€ํ•ด์„œ๋Š” ๋‚ด๋ฆผ์ฐจ์ˆœ
       return 1;
     }
   }
   return -1;
 }
}

// main์—์„œ ์‚ฌ์šฉ๋ฒ•
List<Point> pointList = new ArrayList<>();
pointList.add(new Point(x, y));
MyComparator myComparator = new MyComparator();
Collections.sort(pointList, myComparator);
  • ์ขŒํ‘œ๊ฐ€ ์ฆ๊ฐ€ํ•˜๋Š” ์ˆœ, x์ขŒํ‘œ๊ฐ€ ๊ฐ™์œผ๋ฉด y์ขŒํ‘œ๊ฐ€ ๊ฐ์†Œํ•˜๋Š” ์ˆœ์œผ๋กœ ์ •๋ ฌ

Comparator<Point> myComparator = new Comparator<Point>() {
 @Override
 public int compare(Point p1, Point p2) { ์œ„์™€ ๋™์ผ }
};

List<Point> pointList = new ArrayList<>();
pointList.add(new Point(x, y));
Collections.sort(pointList, myComparator);
  • ์ต๋ช…ํด๋ž˜์Šค๋กœ ๊ตฌํ˜„ํ•œ ๋ฐฉ๋ฒ•

  • ๋‘๊ฐœ์˜ ์ฐจ์ด๊ฐ€ ์žˆ๋‹ค๋ฉด..?

  • ๋‘˜๋‹ค ์ธํ„ฐํŽ˜์ด์Šค

  • ๋งค๊ฐœ๋ณ€์ˆ˜๋ฅผ ๋ช‡๊ฐœ ๋ฐ›๋Š”๊ฐ€ ์ฐจ์ด...?

Last updated