java - Sorting Objects in ArrayList giving unexpected results -
here record arraylist of objects of type employee. trying sort arraylist based on employeename attribute. unfortunately, gives unwanted results.
public void sortbyname(){ for(int = 0; < salesdatamanager.n; i++){ for(int j = i+1; j < salesdatamanager.n; j++){ if(record.get(i).getemployeename().comparetoignorecase(record.get(j).getemployeename()) > 0){ employee etemp = record.get(i); record.add(i,record.get(j)); record.add(j,etemp); } } } displayallrecords(); }
i have gone through other posts in stackoverflow regarding topic , found out of post suggest same way.am doing wrong here?
thanks in advance!
you iterating record
list , according condition determining add current element. however, aren't emptying list first, approach inevitably lead duplications.
java, luckily, has built mechanism such sorting - need implement comparator
:
public class employeenamecomparator implements comparator<emplyoee> { @override public int compare (employee a, employee b) { return a.getemployeename().comparetoignorecase(b.getemployeename()); }
and use it:
collections.sort (record, new employeenamecomparator());
if you're using java 8, use new cleaner syntax:
collections.sort (record, (a, b) -> a.getemployeename().comparetoignorecase(b.getemployeename());
Comments
Post a Comment