![](/img/trans.png)
[英]ArrayList: How to arraylist.set when you have multiple setters
[英]ERROR when appending ArrayList.remove and ArrayList.set
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));
}
}
嘗試刪除和設置時返回錯誤。 這是用於從nlogn中計算V中最長的ascendind子字符串的算法的一部分。每次轉到“ else”時,都會出現錯誤:
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)
binarySearch函數為:
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;
}
我還沒有完全理解您的算法,但是異常情況意味着一時, M
的大小為1,並且您的binarySearch
方法將返回1; 因此,您將嘗試從M
刪除索引1,但索引1不存在(只有索引0)。
它與M.set
,錯誤發生M.set
一行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.