java.lang.Comparable
[sourcecode language=”java”]Comparable.compareTo(Object toCompare)
[/sourcecode]1. positive – if ( currentObject > compareToObject)
2. zero – if ( currentObject == compareToObject)
3. negative – if ( currentObject < compareToObject)
[sourcecode language=”java”] public class Bicycle implements Comparable {private int size;
public void setSize(int size) {
this.size = size;
}
public int getSize() {
return size;
}
@Override
public int compareTo(Object arg0) {
Bicycle bicycleCompareTo =(Bicycle) arg0;
if ( this.bicycleId > bicycleCompareTo.bicycleId ) {
return 1;
} else if ( this.bicycleId < bicycleCompareTo.bicycleId ) {
return -1;
} else {
return 0;
}
}
}
[/sourcecode]
Collections.sort(List)
[/sourcecode]
java.util.Comparator
Comparator.compare(Object obj1, Object obj2)
[/sourcecode]1. positive – if ( o1 > o2 )
2. zero – if ( o1 == o2 )
3. negative – if ( o1 < o2 )
Collections.sort(List, Comparator)
[/sourcecode] @Override
public int compare(Bicycle bicycle1, Bicycle bicycle2) {
if ( bicycle1.getSize() > bicycle2.getSize() ) {
return 1;
} else if ( bicycle1.getSize() < bicycle2.getSize() ) {
return -1;
} else {
return 0;
}
}
}
[/sourcecode]