java实现comparable接口注意


public class LabelViewModel implements Serializable,Comparable {

    public String label;
    public List contactList;

    @Override
    public int compareTo(Object o) {
        if(o instanceof LabelViewModel){
            String join = String.join("", SideBar.b);
            LabelViewModel model = (LabelViewModel)o;
            return join.indexOf(model.label.toUpperCase());
        }else{
            //return 0;
        }
        o = (LabelViewModel)o;
        String join = String.join("", SideBar.b);
        return join.indexOf(o.label.toUpperCase());
    }
}

o自己强转类型为LabelViewModel居然不行,

o = (LabelViewModel)o;
String join = String.join("", SideBar.b);
return join.indexOf(o.label.toUpperCase());

只有这样两种方式写:

join.indexOf(((LabelViewModel)o).label.toUpperCase());
 LabelViewModel model = (LabelViewModel)o;
 return join.indexOf(model.label.toUpperCase());

排序两种使用方式使用:

                Collections.sort(labeltViewModelList);
                labeltViewModelListStore.sort((o1, o2) -> {
                    Log.i(TAG, "compare: "+SideBar.b.toString());
                    String join = String.join("", SideBar.b);

                    return join.indexOf(o1.label.toUpperCase())-join.indexOf(o2.label.toUpperCase());
                });

 ____________________ ________

其实接口加上泛型

就好了

public class LabelViewModel implements Serializable,Comparable {

    public String label;
    public List contactList;

    @Override
    public int compareTo(LabelViewModel o) {
        String join = String.join("", SideBar.b);

        if(o instanceof LabelViewModel){
            return join.indexOf(((LabelViewModel)o).label.toUpperCase());
        }else{
             return 0;
        }
    }
}

相关