Comparable Interface
What is an Interface in Java: A list of methods you must code when you implement it. A variable type that cannot be instantiated.
Why implement a Comparable interface: You can then use Collections.sort, a very helpful method.
How to implement Comparable inside a class:
Class header must have : implement Comparable <T> (with T being your class type)
Add a method: public int compareTo(yourclass o)
return: a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.
Example:
import java.util.ArrayList;
class Person implements
Comparable<Person> {
private
String name;
private
String lastname;
public
Person(String name, String lastname) {
this.name = name;
this.lastname = lastname;}
public
String toString(){ return name + " " + lastname;};
@Override
public
int compareTo(Person person)
{
int len1 = name.length();
int len2 = person.name.length();
if(len1
> len2) { return 1; }
else
if(len1 < len2) { return -1; }
else
{
return name.compareTo(person.name);
}
}
}
import java.util.ArrayList;
import java.util.Collections;
public class
App {
public
static void main(String[] args)
{
ArrayList<Person> list = new
ArrayList<Person>();
list.add(new Person("Zoe", "Jones"));
list.add(new Person("Sue", "Willis"));
Collections.sort(list);
for
(Person p : list){
System.out.println(p);
}
}
}