radiopassive
radiopassive

Reputation: 566

Sorting Objects in ArrayList giving unexpected results

Here record is an ArrayList of objects of the type Employee. I am trying to sort the ArrayList based on the employeeName attribute. Unfortunately, it gives unwanted results.

public void sortByName(){       
    for(int i = 0; i < 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 this topic and found out that most of the post suggest this same way.Am I doing something wrong here?

Thanks in advance!

Upvotes: 1

Views: 87

Answers (2)

radiopassive
radiopassive

Reputation: 566

@Howard Wang and Mureinik, you guys were right. The add(index,object) method added the object to the index and was right-shifting the already existing object, instead of replacing it, which was what I was intending to achieve. So, adding record.remove(i+1); and record.remove(j+1); to the code did the trick!

public void sortBySales()
{



    for(int i = 0; i < SalesDataManager.N; i++)
    {
        for(int j = i+1; j < SalesDataManager.N; j++)
        {

            if(record.get(i).getEmployeeSales() > record.get(j).getEmployeeSales())
            {


                Employee etemp = record.get(i);
                record.add(i,record.get(j));
                record.remove(i+1);
                record.add(j,etemp);
                record.remove(j+1);

            }   

        }

    }




}

Upvotes: 0

Mureinik
Mureinik

Reputation: 311338

You are iterating the record list and according to some condition determining where to add the current element. However, you aren't emptying the list first, so this approach will inevitably lead to duplications.

Java, luckily, has a built it mechanism for such sorting - you just need to implement a Comparator:

public class EmployeeNameComparator implements Comparator<Emplyoee> {
    @Override
    public int compare (Employee a, Employee b) {
        return a.getEmployeeName().compareToIgnoreCase(b.getEmployeeName());
}

And then just use it:

Collections.sort (record, new EmployeeNameComparator());

If you're using Java 8, you could also use the new cleaner syntax:

Collections.sort
  (record, (a, b) -> a.getEmployeeName().compareToIgnoreCase(b.getEmployeeName());

Upvotes: 3

Related Questions