Let us take array of integers.
Now, how will you print the numbers in ascending order? You can use Arrays class to sort any type of arrays as follows,
Now assume that you are designing an employee management system. So you will have a class to represent the employee details. Let’s call that class as Employee.
Now you can use the Collections class to sort this employee collection as mentioned before.
int[] numbers = new int[] {2,5,4,8,9};
Now, how will you print the numbers in ascending order? You can use Arrays class to sort any type of arrays as follows,
java.util.Arrays.sort(numbers);
System.out.println(Arrays.toString(numbers));
Your output will be [2, 4, 5, 8, 9]. How can you achieve the same if the data structure is a collection? You can use the class java.util.Collections as follows,
List<Integer> numberList = new ArrayList<Integer>(Arrays.asList(2, 5, 4, 8, 9));
Collections.sort(numberList);
System.out.println(numberList.toString());
Now assume that you are designing an employee management system. So you will have a class to represent the employee details. Let’s call that class as Employee.
class Employee {
String name;
int employeeNo;
...
}
Assume that each division maintains a collection of employees. Now you are asked to list the employees in each division in ascending order sorted by employeeNo. You may think what is wrong in using the java.util.Collections class. Yes, you are right. Nothing is wrong; but how will you compare employee object unlike integers, which are numeric types?
You will have to make the employee object comparable to itself. There comes the interface java.lang.Comparable to save you. All you need to do is, implement this interface and provide definition for compareTo method. That’s all.
public class Employee implements Comparable<Employee> {
private String name;
private int employeeNo;
public int compareTo(Employee e) {
return employeeNo - e.employeeNo;
}
}
Now you can use the Collections class to sort this employee collection as mentioned before.
List<Employee> empList = ...
Collections.sort(empList);
Comments
Post a Comment