Archive

Posts Tagged ‘sorting’

Java Sorting using Comparator

May 24th, 2010

Lets see how we can sort our Employee objects using different criteria like id, name, salary.

SortTest remains the main class that will perform creating and filling objects for us. This time employee class is plain old java classs that holds some data about each employee we create.

Here I have created scenarios or you can say strategies OR classes for sorting as SortById,  SortByName, SortBySalary. Each of above class implements comparator interface and overrides compare method, which takes two objects to compare and return eithre -1, 1 or 0.

Note: I have added few helper functions that really helps while coding like  print - this takes array list of objects and prints in format I want instead of class id and all that. toString -  overridden this function so I can return the class string as required

Here goes the code -
Read more…

Java , ,

Java Sorting using Comparable

May 24th, 2010

In Java you can do sorting by implementing 2 interfaces
1) Comparable
2) Comparator

Here we will see sorting example using Comparable Interface. As an example we will be sorting objects of Employee class.

When using comaprable interface make sure the object class
which you are sorting implements comaprable interface and override compareTo method correctly.

As I was more used to Java 1.4, I didnt followed any Java Generics implemetation.

SortTest is main class that will actually creaate an array list and fill it with some random Employee objects.

Employee is class that will implement compareTo method. I have added simple if-else control structure that will decide what to return on the basis of employee id.
less : -1           equal : 0           greater : 1

Here is the code for classes:
Read more…

Java , , , ,