Comparable Interface in java for handling Employee data

 If you want to define the natural ordering of objects, use the ‘Comparable’ interface.

Syntax is given below…

Public interface Comparable <T> }

  Member variables

  Member function()1 {  ….. }

  ………………………………………..

 Member Functionn {……..}

Let us create a Employee list with name and id using this interface.

  • className: Employee
  • Constructor: Employee()
  • Overridden function:
  • compareTo() and toString()

Steps to follow:

  • A list ‘Employee’ is created using ArrayList.
  • In the constructor, assign the values for id and Name.
  • CompareTo – Comparing o lists
  • ToString -converts to string.
  • In side main() function, add the values to the Employee List.
  • Finally,display it.

Program:

import java.util.*;

// class creation with memeber functions and variables

class Employee implements Comparable<Employee> {

    String name;

    int id;

    //Constructor

    public Employee(String name, int id) {

        this.name = name;

        this.id = id;

    }

    // overriding methods

    @Override

    public int compareTo(Employee offline) {

        return this.id - offline.id;

    }

    @Override

    public String toString() {

        return name + ": " + id;

    }

    //main() function

    public static void main(String[] args) {

        List<Employee> emp = new ArrayList<>();

        emp.add(new Employee("Ashok", 02));

        emp.add(new Employee("Karthik", 14));

        emp.add(new Employee("Balu", 05));

        emp.add(new Employee("Sunny",56));

        emp.add(new Employee("Ranjith", 28));

                Collections.sort(emp);

        for (Employee emp1 : emp) {

            System.out.println(emp1);

        }

    }

}

Output:

C:\raji\blog>javac Employee.java

C:\raji\blog>java Employee

Ashok: 2

Balu: 5

Karthik: 14

Ranjith: 28

Sunny: 56

This is the simple way of implementing ‘Comparable’ interface in java.

No comments:

Post a Comment