Menu
Coddy logo textTech

Recap - Custom Collection

Part of the Object Oriented Programming section of Coddy's Dart journey — lesson 75 of 110.

challenge icon

Challenge

Easy

Let's build a ScoreBoard system that tracks player scores and demonstrates how special methods work together to create a polished, professional class!

You'll organize your code into two files:

  • score_board.dart: Create a Player class and a ScoreBoard class that work together to manage game scores.

    Your Player class should have a name (String) and score (int). It needs to:

    • Implement Comparable<Player> so players can be sorted by score in descending order (highest first)
    • Override == and hashCode so two players with the same name are considered equal (regardless of score)
    • Override toString() to return: [name]: [score] points

    Your ScoreBoard class should store a list of players and provide:

    • An addPlayer(Player player) method that adds a player only if they don't already exist (use your equality implementation!)
    • A call() method that takes no arguments and returns a sorted copy of the players list (sorted by score, highest first)
    • Override toString() to display all players (unsorted), one per line, with the header ScoreBoard: on the first line
  • main.dart: Import your score board file and demonstrate how all these special methods work together:
    • Create a ScoreBoard
    • Add these players: Alice with 150, Bob with 200, Charlie with 175
    • Try adding Alice again with score 999 (it should be rejected as a duplicate)
    • Print the scoreboard using its toString()
    • Print an empty line
    • Print Rankings:
    • Call the scoreboard like a function to get sorted rankings, then print each player

This challenge brings together toString() for display, == and hashCode for duplicate detection, compareTo() for sorting, and call() for a clean callable interface!

Expected output:

ScoreBoard:
Alice: 150 points
Bob: 200 points
Charlie: 175 points

Rankings:
Bob: 200 points
Charlie: 175 points
Alice: 150 points

Try it yourself

import 'score_board.dart';

void main() {
  // TODO: Create a ScoreBoard

  // TODO: Add players: Alice (150), Bob (200), Charlie (175)

  // TODO: Try adding Alice again with score 999 (should be rejected as duplicate)

  // TODO: Print the scoreboard using its toString()

  // TODO: Print an empty line

  // TODO: Print "Rankings:"

  // TODO: Call the scoreboard like a function to get sorted rankings, then print each player
}

All lessons in Object Oriented Programming