AnZyuZya
AnZyuZya

Reputation: 201

Comparator of ArrayList<Object> doesn't work properly

Please help me to solve this problem. I've been trying to write different comparators already and none of them works properly.

They like sort by parts. Let it be values like: 0, 4, 1, 9 , 18, 3, 18, 9.

And it sorts like this: 9, 9, 0, 1, 3, 18, 18, 4.

Some "ordered" random I would say.

Please help to find what I did wrong.

Class with data and Comparator:

public class CoursesData {
private String url;
private String name;
private String lessonsCount;
private String isFree;
private String price;
private String language;
private String difficulty;

private AuthorData author;

public static Comparator<CoursesData> CoursesDataPriceComparator = new Comparator <CoursesData> () {
    public int compare (CoursesData left, CoursesData right){
        return right.getPrice().compareTo(left.getPrice());
    }
};

....(getter-setters)

And how I use this comparator:

    ArrayList<CoursesData> coursesDatas = parserJson.getCourses();
    Collections.sort(coursesDatas, CoursesData.CoursesDataPriceComparator);
    mAdapter = new CoursesItemAdapter(getActivity(),
            R.layout.catalog_list_item, coursesDatas);

Price is String but with digit values. Maybe its the problem...

Thanks for any help.

Upvotes: 1

Views: 539

Answers (1)

Boris Pavlović
Boris Pavlović

Reputation: 64622

Replace

return right.getPrice().compareTo(left.getPrice());

with

return new Double(right.getPrice().trim()).compareTo(
  new Double(left.getPrice().trim())
);

Upvotes: 1

Related Questions