Implement Comparable

Report a typo

Imagine you write a simple class called Cake:

public class Cake {
    private String name;
    private String description;
    private int weight;

    // constructor

    // getters and setters
}

You want to define the ordering by name. Which of the examples below is correct?

  1. public class Cake {
        private String name;
        private String description;
        private int weight;
    
        // constructor
    
        // getters and setters
    
        @Override
        public int compareTo(Cake otherCake) {
            return getName().compareTo(otherCake.getName());
        }
    }
  2. public class Cake implements Comparable<Cake> {
        private String name;
        private String description;
        private int weight;
    
        // constructor
    
        // getters and setters
    
        @Override
        public int compareTo(Cake otherCake) {
            return getName().compareTo(otherCake.getName());
        }
    }
  3. public class Cake implements Comparable<Cake> {
        private String name;
        private String description;
        private int weight;
    
        // constructor
    
        // getters and setters
    
        @Override
        public int compareTo(Cake cake, Cake otherCake) {
            return cake.getName().compareTo(otherCake.getName());
        }
    }
  4. public class Cake implements Comparable<Cake> {
        private String name;
        private String description;
        private int weight;
    
        // constructor
    
        // getters and setters
    
        @Override
        public int compareTo(Cake otherCake) {
            return otherCake.getName().compareTo(getName());
        }
    }
Select one option from the list
___

Create a free account to access the full topic