Java 如何打印一个无序排列的ArrayList?
如何打印一个无序排列的ArrayList?这就是我到目前为止所做的:Java 如何打印一个无序排列的ArrayList?,java,arraylist,Java,Arraylist,如何打印一个无序排列的ArrayList?这就是我到目前为止所做的: public class RandomListSelection { public static void main(String[] args) { String currentDir = System.getProperty("user.dir"); String fileName = currentDir + "\\src\\list.txt"; // Cre
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();
}
}
试试这个
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);
}
试试这个
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);
}
为了删除单个空值,只要有行,就应该只读取并添加到集合中 在代码中,您将字符串设置为null,读者无法读取任何其他内容,并将仍然为null的字符串添加到列表中。然后,检查字符串是否为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();
}
为了删除单个空值,只要有行,就应该只读取并添加到集合中 在代码中,您将字符串设置为null,读者无法读取任何其他内容,并将仍然为null的字符串添加到列表中。然后,检查字符串是否为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();
}
我希望能够将文件中的行添加到ArrayList,以便在循环中对其进行初始化。那么糟糕吗?我对代码做了一些修改。好的,现在您正在打印无序排列的ArrayList。问题是什么?好的,我在上面已经解决了。看一看。@MarkoTopolnik是的,你是对的,我对它是其他东西感到困惑。我想能够将我的文件中的行添加到ArrayList中,所以我已经在循环中初始化了它。那么糟糕吗?我对代码做了一些修改。好的,现在您正在打印无序排列的ArrayList。问题是什么?好的,我在上面已经解决了。看一看。@MarkoTopolnik是的,你是对的,我对它是其他东西感到困惑。