我目前有一个包含名为' People'的对象的数组。每个人都有一个名字,日,月,年(出生)。我想将这些转换为日期并使用.isAfter()方法来比较它们并求助它们,但它根本不按日期对它们进行排序。这是一个更简单的代码版本
for (int i = 0; i<peopleArray.size()-1; i++)
{
for (int j = 0; j<peopleArray.size()-1; j++)
{
LocalDate firstDate = LocalDate.of(Integer.parseInt(peopleArray.get(i).getDOBYear()),
Integer.parseInt(peopleArray.get(i).getDOBMonth()),
Integer.parseInt(peopleArray.get(i).getDOBDay()));
LocalDate secondDate= LocalDate.of(Integer.parseInt(peopleArray.get(j).getDOBYear()),
Integer.parseInt(peopleArray.get(j).getDOBMonth()),
Integer.parseInt(peopleArray.get(j).getDOBDay()));
if(firstDate.isAfter(secondDate))
{
Person temp = peopleArray[i];
peopleArray[i] = peopleArray[i+1];
peopleArray[i+1] = temp;
}
}
}
&#39;人&#39;是对象的名称。非常感谢您的帮助!
答案 0 :(得分:1)
正如user2004685和duffymo所说,你需要编写一个自定义compareTo
,示例user2004685对我来说是正确的(目前我在这台计算机上没有编译器。)
我建议的一个附录是你可能不想要一个People
类 - 也许你只是想要你现在拥有的数组,并且你并不总是希望对Person
的实例进行排序你描述的方式。如果是这样,那么要做的就是将Comparator
传递给Arrays.sort()
:
Arrays.sort(people, new Comparator<Person>() {
public int compare(Person p1, Person p2) {
// implement Person.getDOB() in the appropriate way
return p1.getDOB().compareTo(p2.getDOB());
}});
或者,如果你使用Java8,你可以用lambda更简洁地做到这一点:
Arrays.sort(people, (p1,p2) -> p1.getDOB().compareTo(p2.getDOB()));
答案 1 :(得分:0)
根据duffymo
建议,您只需在Comparable
类上实现People
接口,如下所示:
public class People implements Comparable<People> {
/* Members */
private String name;
private int dobDay;
private int dobMonth;
private int dobYear;
/* Getter, Setter, Constructor */
/* Get Date Function */
private Date getDate() {
return LocalDate.of(this.dobYear, this.dobMonth, this.dobDay);
}
@Override
public int compareTo(People people) {
return this.getDate().isAfter(people.getDate());
}
}
最后按如下方式对数组进行排序:
Collections.sort(peopleArray);
答案 2 :(得分:0)
如果您在java中寻找更简单的解决方案,那么<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/listView" />
</LinearLayout>
的解决方案就应该这样做。
由于您已标记user2004685
,我猜您在代码中需要有关此问题的帮助。
<强>的问题:强>
bubble-sort
。i/j < size()
和i
位置的元素,但需要交换j
和i
代码更正:
i+1