Reputation: 57
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.
Upvotes: 2
Views: 86
Reputation: 10882
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.
Upvotes: 0
Reputation: 4673
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.
Upvotes: 3
Reputation: 1480
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.
Upvotes: 1