Session 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 bases 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 area of triangles (not triangle edges), we have to upgrade 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.:
ArrayList
implements a fast search of an element by its index;LinkedList
implementation allows a fast insertion and removal of elements by indexes.
Useful link: Check API and have a look at methods.
3. java.lang.Iterable
Iterable
interface describes method iterator
. Iterations are useful for discovering content of objects. For example, ArrayList
implements Iterable
interface. In the following syntax for (T element : elements)
, Java does not control if elements are placed in an array or a list; Java controls if the data type is Iterable
. That means that everyone can create a class whose content can be looked through using for
loop.
Useful link: Check API and have a look at methods.
Session 6 |