【问题标题】:Sorting arraylist in android not working在android中排序arraylist不起作用
【发布时间】:2014-05-16 10:53:27
【问题描述】:

我在类约会对象的数组列表上调用 collections.sort,但它不会对任何事情进行排序

这就是我调用集合排序的方式

 ArrayList<appointment> listoffappointments = new ArrayList<appointment>();

 //then everytime on button click user adds a new appointment after setting the following code is executed 
{
 Calendar calendar1 = Calendar.getInstance();                
 calendar1.set(mYear, mMonth, mDay, temphour, tempmin);
 appointment tempppt = new appointment(c2,tempstring1);
 listoffappointments.add(tempppt);
 Collections.sort(listoffappointments);
}

这是课程,有人可以找到问题,谢谢

import java.util.Calendar;

public class appointment  implements Comparable<appointment> {

Calendar time;
String Text;
public appointment(Calendar tempc, String temptext) {
    Text = temptext;
    time = tempc;
}

public void settext(String text)
{
    Text = text;
}
public String gettext()
{
    return Text;
}
public String toString() {
    return Text;
}
public Long gettimeofappt()
{
    return time.getTimeInMillis();

}

@Override
public int compareTo(appointment o) {
     return (this.gettimeofappt() < o.gettimeofappt() ) ? -1: (this.gettimeofappt() > o.gettimeofappt() ) ? 1:0 ;  

}


}

【问题讨论】:

  • 您的 collections.sort 调用在哪里?
  • 在我的另一个类中具有类约会对象的数组列表
  • 您应该在问题中包含该代码。
  • 现在将其添加到问题中@nKn
  • 假设我的数组列表中已经有约会类型的元素

标签: android sorting arraylist comparable compareto


【解决方案1】:

试试这个:

Collections.sort(list, new Comparator<String>() {
        @Override
        public int compare(String s1, String s2) {
            return s1.compareToIgnoreCase(s2);
        }
    });

Sorting ArrayList (String ArrayList and custom class)

【讨论】:

    【解决方案2】:

    你正在返回一个 Long 对象,改变你的 compareTo 喜欢:

    @Override
    public int compareTo(appointment o) {
         return this.gettimeofappt().compareTo(o.gettimeofappt() );
    
    }
    

    Long.compareTo 比较两个 Long 对象的数值,而 Retunrs:

    如果这个 Long 等于参数 Long,则值为 0;少一个值 如果此 Long 在数值上小于参数 Long,则大于 0;和一个 如果此 Long 在数值上大于 参数 Long(有符号比较)。

    【讨论】:

    • 即使使用“return this.gettimeofappt().compareTo(o.gettimeofappt());”没有任何改变@blackbelt
    • 你能打印出 ArrayList 的内容吗?仅用于调试目的
    • 数组列表的内容完全按照它们进入的顺序出现,所以首先然后第一第二然后第一第二第三
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多