Sorting in Java – Take 1

The class java.util.Collections provides many utility methods for simplifying the most commonly used operations. One of the methods available in that class is sort() which is used for sorting elements. Let us the see how the Collections.sort() method operates on pre-defined data-types as well as user-defined data-types.
Consider the following code snippet that will sort a list of numbers.

List<integer> numbers = Arrays.asList(1, 5, -4);
Collections.sort(numbers);
System.out.println(numbers);
The method Arrays.asList() creates a new ArrayList object and then populates the list with elements 1, 5 and -4. Then a call is made to Collections.sort() method by passing the collection object. The sort() method directly modifies the collection object after the sorting operation.

What will happen if the Collections.sort() method is passed with a List of user-defined objects? Now, it is the programmer’s responsibility to provide a hint to the sort() method on how sorting has to be done on user-defined objects. Given two user-defined objects o1 and o2, it should be mentioned how to determine whether two objects are equal , whether o1 is greater than o2 or o1 is smaller than o2. So, this can be specified to the Collections.sort() method. There is one more variation of the Collections.sort() that accepts two arguments, one is the list of objects to be sorted and the other is a Comparator object that contains the essential logic for sorting.

package Loops;
 /** * * @author Ashish Dutt */
public class Movie
{
 private String name; private int rank;
 // Creating Constructor that takes two parameters
 public Movie(String name, int rank)
 { this.name = name;
 // the class or instance variables being initialised by the parameters
 this.rank = rank;
 } // creating getter method.. An example of encapsulation public
 String getName()
 {
 return name;
 } // creating setter method
 public void setName(String name)
 {
 this.name = name;
 }
 public int getRank()
 {
 return rank;
 }
 public void setRank(int rank)
{
 this.rank = rank;
 } // returning the variable values.
 public String toString()
{
 return name + rank;
 }
 }

Advertisements