Java

OOP GUIDE / WORK

 

LINE CLASS

 

Topics

  • Implementing the Comparable interface
  • Implementing the compareTo method
  • Sorting ArrayLists with Comparable

 

 

TASK – PART 1 – BASIC LINE CLASS


Create a Line class with the following specifications:

 

  • It has four instance variables x1, y1, x2 and y2;
  • It has a constructor that gets a parameter for each instance variable.
  • It has a length method that returns the length of the line. 
  • It also a toString() method returns a string similar to:

                    (2,5) to (5,5) [length=3]

 

 

TASK – PART 2 – ARRAYLIST

 

In main of a Tester class, create an ArrayList with at least five different Line objects in it.  Output the content of the ArrayList to screen.

 

 

TASK – PART 3 – IMPLEMENT COMPARABLE

 

We now want to sort the Line objects in the ArrayList by length.  The easiest way to do this is to make the Line class implement the Comparable interface.  Make it so.

 

 

TASK – PART 4 – SORTING

 

Now that Line objects can be compared, we can use Collections.sort() to sort lines.  Sort the ArrayList and output it to screen to confirm that the sorting is working correctly.