Lesson 22 – Comparable Interface

When you come in
- Connect to the Internet
- Log in to Piazza
- Start Bluej
- Navigate to laughton.com/obrien/sjsu/cs46a/CRT_lessons/ and open this lesson
Activity - Comparable interface in the String class
Record your participation in Piazza clicker question Lesson22 Q1
- String class implements Comparable. How could you find out for yourself if it implemented Comparable?
- Let's look at how Strings are compared
- What do these comparisons return?
- "hello".compareTo("help")
- "help".compareTo("hello")
- "help".compareTo("help")
- "Help".compareTo("apple")
- "999".compareTo("apple")
Why implement the Comparable interface in your classes
- Allows you to use a library utility to sort an array or ArrayList containing objects of your class.
- Arrays.sort for arrays or Collections.sort for ArrayLists
- Download and open comparable_interface.zip
- Look at ComparableTester.
- We want to sort the array of BankAccounts.
Activity - Try to sort BankAccounts
Record your participation in Piazza clicker question Lesson22 Q2
- Open the comparable_interface project
- What happens when you compile ComparableTester?
- What happens when you execute the main method?
- Why?
Activity - Implementing Comparable interface in BankAccount
Record your participation in Piazza clicker question Lesson22 Q3
Let's fix the problem by implementing the Comparable interface.
- The class header needs to specify that we are implementing Comparable interface
- BankAccount already implements one interface
- To add another add a comma and the new interface name
, Comparable
- Won't compile. Why? What message do you get?
- Add the required method from the interface, compareTo, as a stub. Compile
- Now implement the body of the compareTo method ordering by
balance
- If the balances are equal, order by accountId
Activity - A trick for comparing doubles
Record your participation in Piazza clicker question Lesson22 Q4
Activity - Implementing Comparable interface in Student
Record your participation in Piazza clicker question Lesson22 Q5
Add the Comparable interface to the Student class. Students are ordered by GPA. If the GPA's are the same, they are ordered by name. Uncomment the code in ComparableTester that creates the ArrayList and sorts it.
- Got it
- Got it but it was hard
- Didn't get it
Activity - Creating Comparable objects
Record your participation in Piazza clicker question Lesson22 Q6
What would happen if you tried to compile these statement
- Comparable c = new Comparable();
- Comparable c = new Student("Alice", 3.2);
- Comparable c1 = new Rectangle(10, 20, 30, 40); (Look in the Rectangle API)