Saturday, 15 January 2011

java - How do you properly use the compareTo method implemented in String? -



java - How do you properly use the compareTo method implemented in String? -

so created employee object , driver. driver contains arraylist of employees, , particular method returns employee name comes first alphabetically.

let's add together 2 employees arraylist 'staff' , phone call them "a" , "z".

for reason, returns employee "z" when expect homecoming employee "a". using compareto method correctly, or else entirely?

public employee first() { int guy = 0; ( int x = 1 ; x < staff.size() ; x ++ ) { if ( staff.get( x -1 ) instanceof employee && staff.get( x - 1 ).getname().compareto( staff.get( x ).getname() ) < 0 ) guy = x - 1; } homecoming ( (employee) staff.get( guy ) ); }

no need reinvent wheel. create utilize of custom comparator , utilize collections sorting methods.

public class namecomparator implements comparator<employee> { @override public int compare(employee o1, employee o2) { homecoming o1.getname().compareto(o2.getname()); } } collections.sort(yourarraylist, new namecomparator());

alternatively, can ensure employee class implements comparable<employee> , can without custom comparator above. assumes ever want compare based on names.

java string compareto

No comments:

Post a Comment