Social Media

Tag Archives for " Core Java "

Comparable vs Comparator Comparison

java.lang.Comparable

[sourcecode language=”java”]

Comparable.compareTo(Object toCompare)

[/sourcecode]
  • Natural ordering – eg List of Users ordered by Id
  • Implemented against class
  • Sorting Method – int compareTo(Object o1)
  • CurrentObject vs compareToObject
  • compareTo return –

          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]

  • Calling method –
[sourcecode language=”java”]

Collections.sort(List)

[/sourcecode]

 

 

java.util.Comparator

  • Alternative ordering – eg List of Bicycles ordered by BikeSize
  • Multiple Comparators
[sourcecode language=”java”]

Comparator.compare(Object obj1, Object obj2)

[/sourcecode]
  • Nested static classes
  • Sorting Method – int compare(Object o1, Object o2)

          1. positive – if ( o1 > o2 )

          2. zero if ( o1 == o2 )

          3. negative if ( o1 < o2 )

  • Calling –
[sourcecode language=”java”]

Collections.sort(List, Comparator)

[/sourcecode]
  • Example –
[sourcecode language=”java”] public class BicycleSizeComparator implements Comparator<Bicycle>{

@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]

1 2 3 11