|
How do we do sorting of objects using Collections.sort
method?
A java programmer usually required to do coding to sort a given set of inputs. Java has inbuilt set of API’s for sorting. There is a Comparable interface in java that needs to be implemented by class whose object needs to be compared. Java classes like “Integer”, “Date” implements this interface, so object of these classes can be sorted easily by Collection’s sort method. We can make a class that implements Comparable interface so that it’s objects can be sorted by “Collections.sort” method. Using Collections.sort to sort custom class and user defined Comparator Code: import java.util.ArrayList;
class Employee implements Comparable {
private double salary; Employee(String name, double salary) {
String getName() {
double getSalary() {
public String toString() {
public int compareTo(Object o) {
Employee e = (Employee) o; return name.compareTo(e.getName());
static class SalaryComparator implements Comparator
{
Employee e1 = (Employee)
o1;
return (int) (e1.getSalary()
- e2.getSalary());
class UtilDemo4 {
double[] salaries = { 2.0, 5.0, 6.0, 4.0 }; List l = new ArrayList(); for (int i = 0; i < names.length;
i++)
Collections.sort(l); ListIterator liter = l.listIterator(); while (liter.hasNext())
Collections.sort(l, new Employee.SalaryComparator()); liter = l.listIterator(); while (liter.hasNext())
|
|
Do you have a Java Problem?
Java Books
Return to : Java Programming Hints and Tips All the site contents are Copyright © www.erpgreat.com
and the content authors. All rights reserved.
|