Bound mismatch for java Collections sorting

泄露秘密 提交于 2019-12-01 12:08:53

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/19196393/bound-mismatch-for-java-collections-sorting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!