Removing last random string from arraylist

你离开我真会死。 提交于 2019-12-13 15:22:03

问题


I'm making a program that displays random lines from a file but I'm a bit new to arraylists. I want to remove the most previous random line from the arraylist after it's displayed but not from the file. This is because I don't want it to be repeated. Here's my code:

try {
    Random random = new Random();
    int randomInt = random.nextInt(50);
    FileReader fr = new FileReader(file);
    BufferedReader reader = new BufferedReader(new FileReader(file));
    String line = reader.readLine();
    if (line.contains("!")) {
        List<String> lines = new ArrayList<>();
        while (line != null) {
            lines.add(line);
            line = reader.readLine();
            Random r = new Random();
            String rdmln = lines.get(r.nextInt(lines.size()));
            line1.setText("Line" + rdmln);

I want to be able to remove 'rdmln' from the arraylist after it has been displayed so that it won't be displayed again. Thanks in advance.


回答1:


Check the remove(int index) function. In your case:

//your code
String rdmln = lines.remove(r.nextInt(lines.size()));
//the rest of your code

remove will take it from the list and return it to you for use.




回答2:


You can simply use the remove() method, which returns and removes the first instance of the object you specify:

lines.remove(rdmln);

If you would like some information from Javadocs, here's the link.




回答3:


Removing random element from the list is inefficient. If you want to fetch M random elements from list of N elements, your approach will take O(N * M) steps.

Instead I suggest to read the whole file and then shuffle your list of string using Collections.shuffle (which will take O(N)) and then just display first M elements. This will be O(N + M), which equals O(N), as M <= N.



来源:https://stackoverflow.com/questions/31768175/removing-last-random-string-from-arraylist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!