java - Collections.sort - "should implement java.lang.Comparable"

标签 java android

我有下面的代码来从android中的SQLite数据库获取数据。

SystemCountryListDS system_country_list_ds;
system_country_list_ds.open();
List<SystemCountryList> system_country_list = system_country_list_ds.findAll();

我想按国家/地区名称升序获取此列表。我怎样才能做到这一点?

我尝试在列表中执行此操作:

Collections.sort(system_country_list);

它给了我错误:

inferred type is not within its bound; should implement java.lang.comparable

最佳答案

这意味着SystemCountryListDS没有实现Comparable接口(interface)。 有 Collections.sort 您可以在其中传递比较器 Collections.sort with Comporator

你可以做到

Collections.sort(system_country_list, new Comparator<SystemCountryListDS>() {
            @Override public int compare(SystemCountryListDS  o1, SystemCountryListDS  o2) {
                if (o1 == o2)
                    return 0;
                if (o1 == null)
                    return -1;
                if (o2 == null)
                    return 1;

                String country1  = o1.getCountry();
                String country2  = o2.getCountry();

                if (country1 == country2)
                    return 0;
                if (country1 == null)
                    return -1;
                if (country2 == null)
                    return 1;
                return country1.compareTo(country2);
            }
        });

关于java - Collections.sort - "should implement java.lang.Comparable",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29148193/

相关文章:

android - 如何在注册时发送 Firebase 电子邮件确认?

java - 如何替换 Activity 中的 textChangedListener

java - 如何传递数组的数组(列表的列表)以在 play 框架 2.x 中查看?

android - 将 LatLngBounds 缩小 5%

java - 如何在没有按钮的情况下导航回主要 Activity

java - HashMap 内的 HashMap ?

java - Apache POI .xlsx 读取,Gradle 无法构建

java - 流口水最好成绩为空

java - DAML 使用 Java 绑定(bind)流式传输所有 Activity 合约 - LedgerView

Java:调用未定义类型的方法