ArrayList<Integer> M = new ArrayList<Integer>();
ArrayList<Integer> V = new ArrayList<Integer>();
System.out.println("How many values? ");
Scanner in = new Scanner(System.in);
int noVal;
noVal= in.nextInt();
for(int cn = 0; cn < noVal; cn++){
int intrare;
System.out.print("Introdu elem " + (cn) +" ");
intrare = in.nextInt();
V.add(intrare);
}
in.close();
for(int cn = 0; cn < noVal; cn++){
if(cn==0){
M.add(0);
continue;
}
if(V.get(cn)>= V.get(M.get(M.size()-1)) )
M.add(cn);
else{
M.remove(binarySearch(V.get(cn), M.size(), M)); //here is the problem
M.set(binarySearch(V.get(cn), M.size(), M), V.get(cn));
}
}
It returns error when tring to remove and set. This is a piece from an algorithm for computing in nlogn the longest ascendind substring from V. Everytime it goes to "else", that's the error:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 1, Size: 1
at java.util.ArrayList.rangeCheck(Unknown Source)
at java.util.ArrayList.remove(Unknown Source)
at SirMaximCrescator.main(SirMaximCrescator.java:37)
The binarySearch function is:
public static int binarySearch(int key, int size, ArrayList<Integer> data) {
int low = 0;
int high = size - 1;
while(high >= low) {
int middle = (low + high) / 2;
if(data.get(middle).equals(key)) {
return 0;
}
if(data.get(middle) < key) {
low = middle + 1;
}
if(data.get(middle) > key) {
high = middle - 1;
}
}
return low;
}
I have not fully understood you algorithm, but the exception means that at a moment, M
will have a size of 1 and your binarySearch
method will return 1 ; so you will try to remove index 1 from M
whereas it does not exist (there's only index 0).
It has nothing to deal with the M.set
, the error occurs the line before.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.