Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java warning with implementing Comparable

Tags:

java

I'm trying to use Collections.sort on a ArrayList of custom objects, but I'm getting a warning and I can't figure out why

Warning: Type safety: Unchecked invocation 
sort(ArrayList<CharProfile>) of the generic method sort(List<T>) 
of type Collections

With this code:

ArrayList<CharProfile> charOccurrences = new ArrayList<CharProfile>();

...

Collections.sort(charOccurrences);

And here's my method:

public class CharProfile implements Comparable {

...

@Override
public int compareTo(Object o) {

        if (this.probability == ((CharProfile)o).getProbability()) {
            return 0;
        }
        else if (this.probability > ((CharProfile)o).getProbability()) {
            return 1;
        }
        else {
            return -1;
        }
 }
}
like image 917
Doug Smith Avatar asked Oct 29 '12 13:10

Doug Smith


1 Answers

Comparable should be implemented with type safety, here it is <CharProfile>.

public class CharProfile implements Comparable<CharProfile>{
       @Override
       public int compareTo(CharProfile cp) {
       ...
       }
}
like image 98
Subhrajyoti Majumder Avatar answered Sep 28 '22 22:09

Subhrajyoti Majumder