Home
›
Sort object using comparable interface
Posted by: InstanceOfJava
Posted date:
Dec 8, 2014
/
- package com.instanceofjava;
-
- import java.util.Comparable;
-
- public class Employee implements Comparable<Employee> {
-
- int id;
- String name;
-
- public Employee(int id, String name) {
- this.id=id;
- this.name=name;
- }
-
- public int getId() {
- return id;
- }
-
- public void setId(int id) {
- this.id = id;
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- @Override
- public int compareTo(Employee e) {
-
- Integer i= this.getId();
- Integer j=e.getId();
-
- if (this.getId() == e.getId())
- return 0;
- if (this.getId() < e.getId())
- return 1;
- if (this.getId() > e.getId())
- return -1;
- return 0;
- }
- }
- package com.oops;
- import java.util.ArrayList;
- import java.util.Collections;
- import java.util.Iterator;
- import java.io.*;
- class Main{
-
- public static void main(String args[]){
-
- ArrayList al=new ArrayList();
-
- al.add(new Employee(101,"Indhu"));
- al.add(new Employee(106,"Sindhu"));
- al.add(new Employee(105,"Swathi"));
- Collections.sort(al);
-
- Iterator itr=al.iterator();
-
- while(itr.hasNext()){
-
-
Employee st=(Employee)itr.next();
-
System.out.println(st.id +" "+st.name );
-
- }
- }
-
- }
Output:
No comments