简体   繁体   中英

Bound mismatch for java Collections sorting

Hi need Help regarding java collection sorting. It gives me this error:

Bound mismatch: The generic method sort(List<T>) of type Collections is not applicable for the arguments (List<WifiSSID>). 
The inferred type WifiSSID is not a valid substitute for the bounded parameter <T extends Comparable<? super T>>

My code looks like:

public class WifiSSID {

    public String SSIS;
    public double id;
}


 public class ScanFilterWifiList {

    public ScanFilterWifiList(List<WifiSSID> wifiList) {
        Collections.sort(wifiList);
           //Collections.sort(wifiList, new SortSSIDByid()); tried this also.
    }
}
interface Comparator<WifiSSID>
{
    int compare(WifiSSID obj1, WifiSSID obj2);
}

class SortSSIDByid implements Comparator<WifiSSID>
{
    @Override
    public int compare(WifiSSID ssid1, WifiSSID ssid2) 
    {
        int value = 0; 
        if (ssid1.id > ssid2.id) 
            value = 1; 
        else if (ssid1.id < ssid2.id) 
            value = -1; 
        else if (ssid1.id == ssid2.id) 
            value = 0; 
        return value; 
     }
}

Am I doing anything wrong?

You can't sort a List of objects that don't implement the Comparable interface. Or rather, you can, but you have to provide a Comparator to the Collections.sort() method.

Think about it: how would Collections.sort() sort your list without knowing when a WifiSSID is smaller or bigger than another one?

You want to use Collections.sort(wifiList, new SortSSIDByid());

EDIT:

You defined your own proprietary Comparator interface, and implement this proprietary Comparator interface in SortSSIDByid . Collections.sort() wants an intance of java.util.Comparator . Not an instance of your proprietary Comparator interface, that it doesn't know.

Just add this import import java.util.Comparator;

and remove this interface

interface Comparator<WifiSSID>
{
    int compare(WifiSSID obj1, WifiSSID obj2);
}

Your SortSSIDByid comparator class will now implement java.util.Comparator and that is what is required by the Collections.sort() method.

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