降序数组列表

时间:2016-04-02 21:16:16

标签: java arraylist collections

在这个程序中,我需要按降序显示外部文件中的数组列表。每当我运行程序时,我仍然得到原始列表的相同顺序。我只需要降序部分的帮助。我使用Collections方法来完成这个任务,但是我不认为每当我调用Collections时我都完全理解发生了什么,它只是吐出第一个数组调用引入的数组列表。任何帮助将不胜感激。我在有问题的代码的末尾和开头放了4颗星。

import java.io.*;
import java.util.*;

public class ioStafford {



    public static void revOrder(String x[])
    {

    }

    public static void main(String args[])
    {
        try(BufferedReader fr1 = new BufferedReader(new FileReader("myImport.txt")))
        {

            //Create a new file for the reverse output if it doesn't exist
            File f1 = new File("myOutput.txt");

            //Code for new file creation
            if(!f1.exists())
            {
                f1.createNewFile();
            }

            //Initialize string variables
            String type;

            //Array List to hold text file
            ArrayList<String> names = new ArrayList<String>();


            //Add text file contents to the array list
            while((type = fr1.readLine()) != null)
            {
                names.add(type);
            }

            //Display array list
            System.out.println("Below is the list of animals with a comma and in the original order:");
            System.out.println(names);

            ****//Display information in descending order
            Collections.sort(names, Collections.reverseOrder());
            System.out.println(names);****


            //Convert array list to string and replace commas
            String fornames = names.toString().replace("," , " ");

            //Display altered information
            System.out.println("Here is the list with the commas removed:");
            System.out.println(fornames);                                               
        }

        catch(FileNotFoundException e)
        {
        System.out.println("Please utilize the file named myImport.txt please!");
        }

        catch(IOException e)
        {

        }
    }
}

1 个答案:

答案 0 :(得分:-1)

的地方试试这个
Collections.sort(names, Collections.reverseOrder());

: - &GT;

    Collections.sort(names, new Comparator<String>() {

        @Override
        public int compare(String o1, String o2) {
            return o2.compareTo(o1);
        }
    });