The array list request in the constructor is equal to the array list passed to this class but I try to use it in the function calcHead the elements in the array disappears.
import java.io.*;
import java.util.*;
public class C_SCAN {
private ArrayList<Integer> requests = new ArrayList<Integer>();
C_SCAN(ArrayList<Integer> r){
this.requests = r;
System.out.println(requests.size());
}
public int calcHead(int start , int end) throws IOException {
BufferedWriter writer = new BufferedWriter(new FileWriter("sequence.txt", true));
writer.write(" \nC_SCAN : ");
int THM = 0;
System.out.println(requests.size());
requests.add(start);
sortReq(requests);
int current = requests.indexOf(start);
for(int i = current; i > 0; i--) {
THM += Math.abs(requests.get(i) - requests.get(i - 1));
writer.write(String.valueOf(requests.get(i)));
}
THM += Math.abs(requests.get(0));
THM += end;
THM += end - requests.get(requests.size() -1);
for(int i = requests.size() - 1; i > current + 1; i--) {
THM += Math.abs(requests.get(i) - requests.get(i - 1));
writer.write(String.valueOf(requests.get(i)));
}
writer.write("\ntotal head movement : " + String.valueOf(THM));
writer.close();
return THM;
}
public void sortReq(ArrayList<Integer> requests) {
for(int i = 0; i < requests.size(); i++) {
for(int j = 0; j < requests.size(); j++) {
if(requests.get(j) > requests.get(i)) {
Collections.swap(requests, i, j);
}
}
}
}
}
I can assure you that the constructor list is the same reference as the one in the method
Given that you mention list elements are "gone", you seem to be moving elements around in the list as you're iterating over it (twice) and potentially overwriting them
Debug by printing the list before and after your sort method and I think you'll see an issue
The correct iteration procedure looks like this (start
j = i+1
) so that the indices never match and you don't compare same elements more than oncePlease don't use bubble sort...
Collections.sort()
does the right thing, so no need to implement your own methodAlso, your field initial value is never used, so the class can start like