Write a program to sort employees by their experience. Employee class is not allowed to implement any interface.

Answer: For sorting employees we need to use either Comparable or comparator interface. Since, as per question, the Employee class is not allowed to implement any Interface, only option is, to create a new comparator class that implements Comparator interface.

And in “compare()” method of comparator class, write the comparison code for the employee class on the basis of experience.

Sample:

//Class 
public class Employee {
	private String name;
	private int experience;

	public Employee(String name, int experience) {
		this.name = name;
		this.experience = experience;
	}

	public int getExperience() {
		return experience;
	}

	@Override
	public String toString() {
		return "Employee Name=" + this.name + ", Experience=" + this.experience;
	}
}


//Comparator class
public class ComparatorByExperience implements Comparator {

	@Override
	public int compare(Object o1, Object o2) {

		// Implement to comparison code for employees on the basis of
		// experience.

		Employee e1 = (Employee) o1;
		Employee e2 = (Employee) o2;

		if (e1.getExperience() == e2.getExperience())
			return 0;

		if (e1.getExperience() > e2.getExperience())
			return 1;
		else
			return -1;

	}

}


//Test Class
public class Test {

	public static void main(String[] args) {

		// Create a list that hold employees object
		List list = new ArrayList();
		Employee e1 = new Employee("Steve", 7);
		Employee e2 = new Employee("Jason", 50);
		Employee e3 = new Employee("Tom", 35);
		Employee e4 = new Employee("Taylor", 13);

		// Add employees objects to the list
		list.add(e1);
		list.add(e2);
		list.add(e3);
		list.add(e4);
		// sort
		Collections.sort(list, new ComparatorByExperience());

		// Display the result.
		Iterator itr = list.iterator();
		while (itr.hasNext()) {

			Employee emp = itr.next();
			System.out.println(emp.toString());
		}
	}

}

Related Posts