انتقل إلى المحتوى
أمين أبوزيد
BEG-032

الترتيب والمقارنة

  • 4 درس
  • 40 دقيقة قراءة
  • 2 ساعة تدريب (تقدير)
في هذه الصفحة 8 موضوعات

نص الدروس والتمارين باللغة الإنجليزية، بينما تبقى واجهة الموقع وعناوين الدروس بالعربية.

نظرة عامة

الموضوعات

  • Comparable
  • Comparator
  • ترتيب المجموعات

تعلّم أولًا

40 دقيقة قراءة · 2 ساعة تدريب (تقدير)

مخرجات التعلم

  1. Implement Comparable for a natural ordering.
  2. Build Comparators, including multi-key ones with comparing and thenComparing.
  3. Sort lists and use sorted collections (TreeMap, TreeSet) with custom ordering.

الدروس

  1. 01الترتيب الطبيعي باستخدام Comparable10 د قراءة
  2. 02Comparators9 د قراءة
  3. 03الترتيب بعدة مفاتيح10 د قراءة
  4. 04عرض عملي: لوحة متصدّرين بمقارِنات متعددة المفاتيح11 د قراءة

المختبر والتمارين

Lab

BEG-032-LAB1 · Leaderboard

Outcomes: 1–3 · Time: ~1 h Sort players by score descending, then name ascending, and show the top N. Also keep players in a TreeSet using the same comparator. Acceptance: ties ordered correctly.

Exercises (assessment: three exercises)

IDOutcomeTask
BEG-032-EX011Make a Book (title, year) implement Comparable<Book> by year; sort a list of books.
BEG-032-EX022, 3Build a comparator for Book: year descending, then title ascending; sort with it.
BEG-032-EX033Put books in a TreeSet using a title comparator. Add two books with the same title and different years; explain the size.
أظهر الحلول
  • EX01 public int compareTo(Book o){ return Integer.compare(year, o.year); } then Collections.sort(books);.
  • EX02 Comparator.comparingInt(Book::getYear).reversed().thenComparing(Book::getTitle).
  • EX03 The set has size 1 for the duplicated title: the comparator returns 0, so the set treats them as the same element. This is why ordering must match what "equal" means for the set.
  • Subtraction-overflow mistake is covered in demo L04 and quiz Q09.

الاختبار

Outcomes: O1 Comparable · O2 Comparator · O3 sorting and sorted collections.

اختبار ذاتي لك: لا توجد درجات، ولا يُحفظ أو يُرسل أي شيء. اختر إجابة ثم تحقق منها، ويمكنك المحاولة مرة أخرى كما تشاء.

  1. 1Comparable<T> requires which method?O1
  2. 2compareTo returns a positive number when:O1
  3. 3A safe way to compare two ints:O1
  4. 4Comparator.comparing(Player::getName) sorts by:O2
  5. 5To reverse a comparator:O2
  6. 6Use a Comparator rather than Comparable when:O2
  7. 7thenComparing is used to:O3
  8. 8Two elements with compare result 0 in a TreeSet:O3
  9. 9Why is return a - b; risky?O1
  10. 10list.sort(null) or Collections.sort(list) uses:O3

الجزء العملي

Three exercises BEG-032-EX01 to EX03 plus the lab. Pass: all three exercises correct and tied scores ordered by name in the lab.

أخطاء شائعة

Subtraction-based compare (overflow); ordering inconsistent with equals.

التقييم

3 exercises.

الصلة بالمسار الوظيفي

Sorting in APIs (JNR-019) and SQL ORDER BY (BEG-050).

اكتب للبحث في المستويات والمراحل والوحدات والدروس.