运行此文件时,输出到我的文件的文本看起来像这样[Lpeople.Person; @ 33909752,我不确定如何将其更改为人的姓名和年龄
按升序排序
while ((line = reader.readLine()) != null) {
//Creates an integer arraylist peopleAge
Person[] peopleAge = new Person[size];
Person temp = null;
for(int i = 0; i < size; i++) {
peopleAge[i] = entry[i];
}
//k number of passes
for (int k = 1; k < peopleAge.length; k++) {
for(int j = 0; j < peopleAge.length - 1; j++) {
// Compare left to right, not right to left.
if(peopleAge[j].getAge() > peopleAge[j + 1].getAge()) {
//swap peopleAge[j] with peopleAge[j+1]
temp = peopleAge[j];
peopleAge[j] = peopleAge[j + 1];
peopleAge[j + 1] = temp;
}
}
}
System.out.println(peopleAge);
writer.write(peopleAge + System.getProperty("line.separator"));
}
System.out.println("check tempfile");
reader.close();
writer.close();
return null;
}
答案 0 :(得分:1)
Integer.compare()
就足够了:
@Override
public int compareTo(Person person) {
return Integer.compare(this.age, person.getAge());
}
不要忘记为您的课程实现Comparable
:
implements Comparable<Person>
如果您在类中实现了此功能,则可以通过以下方式对Person
个对象的任何数组进行排序:
Arrays.sort(array);
答案 1 :(得分:0)
我看不到您到底是什么问题,但是有一些注意事项。
使用Integer.compare方法和if语句毫无意义。
Integer.compareTo函数返回
因此,如果结果首先是== 0,则
{{1}}
将始终== 0