الترتيب والمقارنة
في هذه الصفحة 8 موضوعات
نص الدروس والتمارين باللغة الإنجليزية، بينما تبقى واجهة الموقع وعناوين الدروس بالعربية.
نظرة عامة
الموضوعات
- Comparable
- Comparator
- ترتيب المجموعات
تعلّم أولًا
40 دقيقة قراءة · 2 ساعة تدريب (تقدير)
مخرجات التعلم
- Implement
Comparablefor a natural ordering. - Build
Comparators, including multi-key ones withcomparingandthenComparing. - Sort lists and use sorted collections (
TreeMap,TreeSet) with custom ordering.
الدروس
المختبر والتمارين
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)
| ID | Outcome | Task |
|---|---|---|
| BEG-032-EX01 | 1 | Make a Book (title, year) implement Comparable<Book> by year; sort a list of books. |
| BEG-032-EX02 | 2, 3 | Build a comparator for Book: year descending, then title ascending; sort with it. |
| BEG-032-EX03 | 3 | Put 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); }thenCollections.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.
اختبار ذاتي لك: لا توجد درجات، ولا يُحفظ أو يُرسل أي شيء. اختر إجابة ثم تحقق منها، ويمكنك المحاولة مرة أخرى كما تشاء.
الجزء العملي
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).