简体   繁体   中英

Java warning with implementing Comparable

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;
        }
 }
}

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

public class CharProfile implements Comparable<CharProfile>{
       @Override
       public int compareTo(CharProfile cp) {
       ...
       }
}

You're using generics, so make the type you pass to the method CharProfile instead of Object .

I'd also recommend rearranging the comparisons as shown, in case that probability is a double.

@Override
public int compareTo(CharProfile o) {

        if (this.probability < o.getProbability()) {
            return -1;
        }
        else if (this.probability > o.getProbability()) {
            return 1;
        }
        else {
            return 0;
        }
}

Noticed that already answered, but here is my input anyway :)

import java.util.ArrayList;
import java.util.List;
import java.util.Collections;

public class CharProfile implements Comparable <CharProfile>{
  public void doStuff(){
    List<CharProfile> charOccurrences = new ArrayList<CharProfile>();
    Collections.sort(charOccurrences);
  }
  @Override
  public int compareTo(CharProfile o) {
    return -1;
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM