Thursday, 14 July 2016

Java Code Showing use of Comparable Interface


class Employee implements Comparable<Employee>{
private String name;
private int id;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Override
public int compareTo(Employee emp) {

return (this.id < emp.id) ? -1 : (this.id > emp.id) ? 1 : 0;
}
}
public class ComparableExample {

public static void main(String[] args) {
Employee e = new Employee();
e.setId(10);
Employee e1 = new Employee();
e1.setId(-1);
Employee e2 = new Employee();
e2.setId(12);
List<Employee> list = new ArrayList<Employee>();
list.add(e);
list.add(e1);
list.add(e2);
Iterator<Employee> it = list.iterator();
Employee emp = null;
System.out.println("BEFORE LIST");
while(it.hasNext()){
emp = it.next();
System.out.println(emp.getId());
}
Collections.sort(list);
Iterator<Employee> it1 = list.iterator();
Employee emp1 = null;
System.out.println("AFTER LIST");
while(it1.hasNext()){
emp1 = it1.next();
System.out.println(emp1.getId());
}
}
}


No comments:

Post a Comment