RiFF RAFF
RiFF RAFF

Reputation: 231

Cannot properly sort through my arraylist

so I'm trying to sort my arraylist of geometric objects in ascending order (by area). However, I'm running into an error

The method add(GeometricObject) in the type ArrayList<GeometricObject> is not applicable for the arguments (double)

in my code block

private static void selectionSort(ArrayList<GeometricObject> list) {
        for (int i = 0; i < list.size(); i++) {
            if (i < list.size() - 1) {
                if (list.get(i).getArea() > list.get(i + 1).getArea()) {
                    double j = list.get(i).getArea();
                    list.remove(i);
                    list.add(i, list.get(i));
                    list.remove(i + 1);
                    list.add(j).getArea();
                    i = -1;
                }
            }
        }

     }

line

list.add(j).getArea();

Again, I'm just trying to sort them in order of their areas so i can later print the array. Any help or pointers in the right direction would be appreciated, thanks!

Upvotes: 0

Views: 50

Answers (2)

Al2O3
Al2O3

Reputation: 3203

Try this:

    Collections.sort(list, new Comparator<GeometricObject>() {
        @Override
        public int compare(GeometricObject o1, GeometricObject o2) {
            if (o1.getGmtModified() != null && o2.getGmtModified() != null){
                if(o1. getArea() < o2. getArea()) {
                    return 1;
                }else if(o1. getArea() > o2. getArea()){
                    return -1;
                }else{
                    return 0;                        
                }
            }
            return 0;
        }
    });

Upvotes: 0

Marquis Blount
Marquis Blount

Reputation: 8095

I think you wanted to do this instead

private static void selectionSort(ArrayList<GeometricObject> list) {
        for (int i = 0; i < list.size(); i++) {
            if (i < list.size() - 1) {
                if (list.get(i).getArea() > list.get(i + 1).getArea()) {
                    GeometricObject j = list.get(i);
                    list.remove(i);
                    list.add(i, list.get(i));
                    list.remove(i + 1);
                    list.add(j);
                    i = -1;
                }
            }
        }

     }

I would consider change j to a more meaningful name. The issue occurred because of incomparable datatypes

Upvotes: 1

Related Questions