selfPointer
selfPointer

Reputation: 349

No suitable method found for Collections.sort()

I am working through some of the examples to learn Java, and it seems that I am not able to use Collections.sort to sort my list. Currently, my codes are following:

// Person class in package application.domain

package application.domain;

public class Person implements Identifiable, Comparable<Identifiable> {
    private String name;
    private String id;

    // ...Constructor...

    // ...Accessors for getName and getPersonID...

    @Override // from interface "Identifiable"
    public String getID(){
        return getPersonID();
    }

    public int compareTo(Identifiable another) {
        return this.getID().compareTo(another.getID()); 
    }

    //... toString ...

}

// Register class implementation

package application.domain; 
import java.util.*;

public class Register {
    private HashMap<String, Identifiable> registered;

    // ...Constructor - initialize hashmap ...

    public void add(Identifiable toBeAdded){
        this.registered.put(toBeAdded.getID(), toBeAdded);
    }

    // get
    public Identifiable get(String id){ return this.registered.get(id); }

    // getAll - must be generalized to work
    public List<Identifiable> getAll(){
        return new ArrayList<Identifiable>(registered.values());
    }

    // sortAndGetEverything (ERROR)
    public List<Identifiable> sortAndGetEverything(){
        List<Identifiable> all = new ArrayList<Identifiable>(registered.values());
        Collections.sort(all); // <- part of code that gives an error
        return all;
    }
} 

with following output:

enter image description here

*Note that comments with ellipses are used to abbreviate irrelevant parts

What I am suspecting is the Person class's toCompare may be the problem since it is comparing the String... however, I looked it up online and it seems that comparing two different strings are valid with .compareTo method. I tried converting ArrayList to List and still have the same error. I am out of idea so I would like to not if anyone have any suggestion on fixing this. Thank you in advance.

Upvotes: 1

Views: 1524

Answers (2)

Chuanyang Hu
Chuanyang Hu

Reputation: 1

You can just add one line in the first java file:

import java.lang.*

I meet the same error as you and I solved it by the solution mentioned above. I think the reason why it happens is that the complier don't recognize the cumtomer compareTo function.

Upvotes: -1

Mustahsan
Mustahsan

Reputation: 3862

You can extend Identifiable interface from Comparable:

public interface Identifiable extends Comparable<Identifiable> {
    String getID();  
}

Now you dont need to implement Comparable in Person class as well, and Collections.sort() should work now

Upvotes: 2

Related Questions