如何从文件中反转 ArrayList?

How to reverse an ArrayList from a file?

这是原题:

Write a program that reads a set of doubles from a file, stores them in an array or ArrayList, and then prints them back out to the console (using System.out.println statements) in REVERSE order.

For example, if the input file input.txt file contains

27.3 45.6 98.3 10.1

The console output will display 10.1 98.3 45.6 27.3

这是我目前的代码:

package reverse;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;


   public class reversed {

public static void main(String[] args) throws FileNotFoundException {
    // TODO Auto-generated method stub

    Scanner numFile = new Scanner(new File("input.txt"));
    ArrayList<Double> list = new ArrayList<Double>();
    while (numFile.hasNextLine()) {
        String line = numFile.nextLine();
        Scanner sc = new Scanner(line);
        sc.useDelimiter(" ");
        while(sc.hasNextDouble()) {
            list.add(sc.nextDouble());
        }
        sc.close();
    }
    numFile.close();
    System.out.println(list);
    }
}

如何反转我创建的 ArrayList?我的代码有效,我只是不知道如何反转它。我应该把代码放在哪里?谢谢!

您不需要反转 ArrayList,只需以相反的顺序重复它即可。像,

for (int i = list.size(); i > 0; i--) {
    System.out.println(list.get(i - 1));
}

如果你必须在迭代前反转List,你可以使用Collections.reverse(List) like

Collections.reverse(list);