i have class employee implementing comparable interface
public class employee implements comparable<employee> { private int id; private string name; private int age; private long salary; public employee(int id, string name, int age, int salary) { this.id = id; this.name = name; this.age = age; this.salary = salary; } @override public int compareto(employee emp) { return (this.id - emp.id); } @override public string tostring() { return "[id=" + this.id + ", name=" + this.name + ", age=" + this.age + ", salary=" + this.salary + "]"; } }
i have employee[]
array sorting array using arrays.sort()
employee[] emparr = new employee[4]; emparr[0] = new employee(10, "mikey", 25, 10000); emparr[1] = new employee(20, "arun", 29, 20000); emparr[2] = new employee(5, "lisa", 35, 5000); emparr[3] = new employee(1, "pankaj", 32, 50000); arrays.sort(emparr);
my question how sorting working internally, emarr[0].compareto(emarr[1])
swap element if required?
i want know how comparison , swapping happening inside? , role comparatable's compareto(object o)
, comparator's compare(o1,o2)
playing ?
comparable
implies natural ordering. speaking if a.compareto(b) == 0
a.equals(b) == true
(this general convention isn't followed).
comparator
utilized when want sort other natural order. example want order array of integers numbers appear first.
arrays.sort()
using merge sort. see arrays api details.
Comments
Post a Comment