|  | Chapter 6 |  | 
Some Java interfaces
1. java.lang.Comparable
Interface Comparable has method compareTo to compare two objects. The interface is used in sorting algorithms. Using different implementations, we can define on what basis the objects can be compared and sorted. It is a very important functionality when we want to compare instances of our own classes. For example, if we want to compare the area of triangles, we have to upgrade the Triangle class as follows:
//modify Triangle class with the following lines, the rest leave unchanged
public class Triangle implements Polygon, Comparable<Triangle> {
  //implement abstract method compareTo of interface Comparable
  public int compareTo(Triangle compareWith) {
    if (this.area() < compareWith.area())
      return -1; // negative value shows that this object is smaller than the argument object (compareWith)
    if (this.area() > compareWith.area())
      return 1; // positive value indicate that this object is larger than the argument object
    return 0; // zero means that both objects have the same area
  }
}
Useful link: Check API and have a look at methods.
2. java.util.List
Interface  List describes functionality that we already know, e.g. add, get and size. List is an interface because it is implemented in different classes, e.g.:
- ArrayListimplements a fast search of an element by its index;
- LinkedListimplementation allows a fast insertion and removal of elements by indexes.
Useful link: Check API and have a look at methods.
3. java.lang.Iterable
The Iterable interface describes the method iterator. Iterations are useful for discovering the content of objects. For example, ArrayList implements the Iterable interface. In the syntax for (T element : elements), Java does not check if elements are placed in an array or a list; Java checks if the data type is Iterable. That means that everyone can create a class whose content can be browsed through using for loop.
Useful link: Check API and have a look at methods.
|  | Chapter 6 |  |