HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Improving Least Recently Used implementation in Java

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
usedrecentlyjavaleastimplementationimproving

Problem

I wrote implementation of LRU in java and want to know if it can be improved further both in space and time complexity.

Input: Number of frames and reference string for pages.

Output: Number of page faults.

Also I am a little skeptical about its correctness because I got 6/10 in my practical lab.

Kindly ignore OOP's aspect of the program.

import java.util.*;
import java.io.*;
class Lru
{
 private static ArrayList arl=new ArrayList();
 private static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
 public static void main(String []args)throws IOException 
 {
     String [] arr;int n,f,pf=0;
     System.out.println("enter the number of frames");
     n=Integer.parseInt(br.readLine());
     System.out.println("enter the reference string");
     arr = br.readLine().split(" ");
     for(String s:arr)
     {
         f=Integer.parseInt(s);
         if(arl.size()<n)
         { ++pf;arl.add(f);}
         else if(arl.contains(f))
         {
          arl.remove(arl.indexOf(f));
          arl.add(f);
         }
         else { arl.remove(0); arl.add(f);++pf;}
     }
     System.out.println("the total no of page faults are "+pf);
 }
}

Solution

Bug

If the input consisted of the same page number over and over, your program would return multiple faults instead of 1, because you made this condition be first:

if(arl.size()<n)
     { ++pf;arl.add(f);}


You should switch the first and second conditions:

if(arl.contains(f)) {
         arl.remove(arl.indexOf(f));
         arl.add(f);
     } else if(arl.size()<n) {
         ++pf;
         arl.add(f);
     } else {
         arl.remove(0);
         arl.add(f);
         ++pf;
     }

Code Snippets

if(arl.size()<n)
     { ++pf;arl.add(f);}
if(arl.contains(f)) {
         arl.remove(arl.indexOf(f));
         arl.add(f);
     } else if(arl.size()<n) {
         ++pf;
         arl.add(f);
     } else {
         arl.remove(0);
         arl.add(f);
         ++pf;
     }

Context

StackExchange Code Review Q#108688, answer score: 4

Revisions (0)

No revisions yet.