如何打印出一个混洗的ArrayList?

时间:2016-09-22 07:58:21

标签: java arraylist

如何打印出混洗的ArrayList?这就是我到目前为止所做的:

public class RandomListSelection {

    public static void main(String[] args) {

        String currentDir = System.getProperty("user.dir");
        String fileName = currentDir + "\\src\\list.txt";

        // Create a BufferedReader from a FileReader.
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(
                    fileName));
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        // Create ArrayList to hold line values
        ArrayList<String> elements = new ArrayList<String>();

        // Loop over lines in the file and add them to an ArrayList
        while (true) {
            String line = null;
            try {
                line = reader.readLine();

                // Add each line to the ArrayList
                elements.add(line);

            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            if (line == null) {
                break;
            }
        }

        // Randomize ArrayList
        Collections.shuffle(elements);

        // Print out shuffled ArrayList
        for (String shuffedList : elements) {
            System.out.println(shuffedList);
        }


        // Close the BufferedReader.
        try {
            reader.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

2 个答案:

答案 0 :(得分:2)

为了删除单个空值,只要有行就应该读取(并添加到集合中)。

在您的代码中,您将字符串设置为null,您的读者无法读取任何其他内容,并将字符串(仍为null)添加到列表中。之后,检查String是否为null并离开循环!

将循环更改为:

// Loop over lines in the file and add them to an ArrayList
String line="";
try{
    while ((line=reader.readLine())!=null) {
        elements.add(line);
    }
}catch (IOException ioe){
    ioe.printStackTrace();
}

答案 1 :(得分:1)

试试这个。

public static void main(String[] args) throws IOException {
    String currentDir = System.getProperty("user.dir");
    Path path = Paths.get(currentDir, "\\src\\list.txt");
    List<String> list = Files.readAllLines(path);
    Collections.shuffle(list);
    System.out.println(list);
}