【发布时间】:2026-02-02 13:20:02
【问题描述】:
这个问题已经在这里问过很多次了。它只是对Finding the 3 most recently modified files in a long list of files 此处提供的解决方案之一的参考。
我尝试向解决方案添加评论,但我没有足够的声誉点来评论,所以我在这里问它。该解决方案提供了一种按上次修改时间对文件进行排序的方法。
public static void sortFilesDesc(File[] files)
{
File firstMostRecent = null;
File secondMostRecent = null;
File thirdMostRecent = null;
for (File file : files) {
if ((firstMostRecent == null)
|| (firstMostRecent.lastModified() < file.lastModified())) {
thirdMostRecent = secondMostRecent;
secondMostRecent = firstMostRecent;
firstMostRecent = file;
} else if ((secondMostRecent == null)
|| (secondMostRecent.lastModified() < file.lastModified())) {
thirdMostRecent = secondMostRecent;
secondMostRecent = file;
} else if ((thirdMostRecent == null)
|| (thirdMostRecent.lastModified() < file.lastModified())) {
thirdMostRecent = file;
}
}
}
该方法将文件数组作为参数,并假设根据最后修改的顺序对它们进行排序。 我从这种方法中不明白的是它如何修改输入数组以便对其中的所有元素进行排序。在代码中,我们也只是改变了局部变量 firstMostRecent、secondMostRecent 和 thirdMostRecent 的值。数组是如何被修改的?我的理解中可能缺少一些东西,但我没有得到它。请澄清我的困惑。
【问题讨论】: