I have declared a class implementing comparable interface and compareTo method comparing two employees using employee id. Created class objects inserted into array list. Now When I use Collections.sort(arrayList Object) it is working fine.I have a confusion in how the comparison differs between comparable and comparator interface.I want to know how comparison happens between a employee id string which purely consists of numbers and other string employee id which has few characters and numbers using both the inerface.
class Velraj implements Comparable<Velraj>{
String id;
String work;
public Velraj(String id, String work){
this.id = id;
this.work = work;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getWork() {
return work;
}
public void setWork(String work) {
this.work = work;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((work == null) ? 0 : work.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Velraj other = (Velraj) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (work == null) {
if (other.work != null)
return false;
} else if (!work.equals(other.work))
return false;
return true;
}
public int compareTo(Velraj o) {
// TODO Auto-generated method stub
return this.getWork().compareTo(o.getWork());
}
}
public class AppMain {
public static void main(String[] args) {
Velraj v1 = new Velraj("16450","Security Specialist");
Velraj v2 = new Velraj("245591","Consultant");
Velraj v3 = new Velraj("RNJIV3664","Java Architecct");
ArrayList<Velraj> a = new ArrayList<Velraj>();
a.add(v1);
a.add(v2);
a.add(v3);
Collections.sort(a);
/*Collections.sort(a, new Comparator<Velraj>(){
public int compare(Velraj o1, Velraj o2) {
// TODO Auto-generated method stub
return o1.getId().compareTo(o2.getId());
}
});*/
for(Velraj v: a){
System.out.println(v.getId() +"--> " +v.getWork());
}
}
}
Output using comparable:
245591--> Consultant
RNJIV3664--> Java Architecct
16450--> System Security Specialist
Output using comparator:
16450--> System Security Specialist
245591--> Consultant
RNJIV3664--> Java Architecct