This question already has answers here:
Java - IndexOutOfBoundsException: Index: 1, Size: 0
(1 answer)
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed last year.
I've got a very annoying problem with some code throwing an IndexOutOfBoundsException and I really cannot understand why. The logcat points to the "addTimetableItem" of the following code which ill explain more on:
if(sortedFridayTimes.size()>0){
insertDay("Friday");
for(int i=1; i<sortedFridayTimes.size()+1;i++){
addTimetableItem(sortedFridayTimes.get(i));
}
}
"sortedFridayTimes" is an ArrayList containing my own "Timetable Entry" objects which I have sorted into order already. First the size is checked to see if there are any objects and if there is then "insertDay" runs which creates a new textview for a title and adds it to the layout (This works fine..).
Inside the for loop the idea is to then add all the objects from the arraylist into the layout. Now I know that the "addTimetableItem" code works as ive tested it already, but my problem is that i cant seem to get the last object out of the arraylist. If I declare the for loop to only run for
"i<sortedFridayTimes.size()"
then the program runs fine but I don't get the last entry in the arraylist which I know exists because I've debugged and watched my variables. On adding the "+1" as shown above I now get the IndexOutOfBoundsException and I really don't know why. As I've said, I've debugged and I know that an entry exists in the arraylist where I'm trying to point to, but it just crashes. I can provide more code if needs be, but does anyone have any ideas please?
You should accept #Tim's or #Graham's answer, this is just an addendum. They're correct about your size()+1 going past the end of the array.
If you're having difficulty using indexes to properly get everything out of the list, you can also try using a for-each loop (depending on the version of the Android SDK you're using). I'm assuming sortedFridayTimes is a list of class TimetableItem since you don't specify.
So this:
if(sortedFridayTimes.size()>0){
insertDay("Friday");
for(int i=1; i<sortedFridayTimes.size()+1;i++){
addTimetableItem(sortedFridayTimes.get(i));
}
}
Becomes this:
if(!sortedFridayTimes.isEmtpy()){
insertDay("Friday");
for(TimetimeItem item : sortedFridayTimes){
addTimetableItem(item);
}
}
A little cleaner if you don't actually need to use i anywhere.
i<sortedFridayTimes.size()+1
You are looping past the last element in the array. Why the +1?
If there are N elements in the array, then the elements are from indexes 0 through to N-1.
So it should be:
for(int i=0; i<sortedFridayTimes.size(); i++) {
The last loop in your for loop runs:
sortedFridayTimes.get(sortedFridayTimes.size())
This will always be out of bounds, because the elements are zero indexed.
For example, if the array size is "5", then you cannot access index "5", because the 5 elements in the array are 0,1,2,3,4.
Related
This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 2 years ago.
The Array containing the object's details is out of bounds. It would say "Index 1 out of bounds for length 1". However When I printing the strings and arrays and it seems to be captured. Even the array lengths are 3 not 1, but still the error persists
Also, initially, I was able to make this work by putting columns.split("\s+") but after a few runs it went back to this Index 1 out of bounds for length 1....
See Image to see how the problem looks.
What did I miss?
Added Println statement to see what it reads per line.
This line is giving error :
String toUnit = columns[1];
I think the value at this index doesn't exist, i.e, the array size is 1.
Possible Root cause : The split is not properly happening or if you are splitting the value, only one value is extracted.
Check the file whether you have set the value or not so that it should be there in the array. Otherwise, you will get that error.
In the while loop, you should print the line before you split it, so that you know what the line contains.
As Nick already suggested, maybe the line is blank or it does not have the FIELD_SEP as per what you expect.
I think you need to check your conversionsFile and somwhere in that file, there might be a line where it will be having only one value/column (i.e not a proper data) instead of having all the three values.
This question already has answers here:
Why does the foreach statement not change the element value?
(6 answers)
Closed 7 years ago.
I have a int[] a, and trying to set every element in the a to be 1. So when I did following code, and printed every element, it shows they are still 0s.
for(int num:a)
num=1;
But if I try below, every element is 1 now. I'm confused. I always thought the 2 for loop have the same functionality. Can anyone tell me why my first try failed? And why it works when i print them? Thanks~~~
for(int num=0;num<a.length;num++)
a[num]=1;
for(int n:a)
System.out.println(n);
Your first loop declares a local variable which only exists inside that loop. Its value iterates over every value in the array. A new memory location is reserved temporarily and given the name "num". Changing contents of that memory location does not modify the values in the "a" array.
Your second loop explicitly accesses memory allocated for the array "a" and changes their contents.
These loops are different. Both in functionality and operations.
The first one - an enhanced-for loop - is giving you each element in the array referenced by the variable a. It is not exposing anything for you to mutate, so assignments to a have no effect on the actual value in the array.
The second loop is simply going through all of the elements in the array, but you are directly working with the array itself at all times, so mutating the values is perfectly possible.
To put this in other terms:
The enhanced-for is going through the array, and providing you a value to use. That value, while originally provided by the array, has no connection to the array otherwise. Any modifications made to the value would not propagate to the array.
The alternative loop is only ever accessing the array contents directly, where it is perfectly possible to make modifications and reassignments to the array.
Thus, if you ever want to set the values of an array to anything other than their default value, then using the second approach is the way to go.
Or...you could use Java 8's Stream API and come up with something like this:
IntStream.iterate(1, (x) -> 1).limit(100).toArray()
I have two dimensional arrayList, and I want to replace the that is set in the program. The problem is, if i replace the value of arrayList by "ONE", it will work, if I replace it by another value bigger than one, the program enters into a loop. I am using the following syntax:
arrayList.get(index).set(index2,VALUE)
Basically this shouldn't be happening, cause I am not changing anything within the loops, or?
My Questions is WHY? and How to fix it?
the code that is (i assume) producing the problems is:
if(mark.get(index1).get(index2) == 1 && mark.get(i-1).get(j) != 1){
// Replace the value
mark.get(i-1).set(j,1);
flag = true;
}
EDIT: I removed my code, cause it gave the impression I wanted help with the code, i had posted it so that you know what I was talking about. thanks
Got what the problem was! All the initials indexes had a value of ZERO, and I had a condition that was checking if it was not ONE(assuming it will be zero anyway). if i changed it to any other value than ONE then in the next repetitions the condition would have been voided.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Android (method for checking an arrays for repeated numbers?)
I've just asked a question and got a few answers and i was very happy to, but there were very complicated answers, I'm quite new to android so can some one maybe give me some example code or some think explained not the complicated. I've tried there code and tried to make sense of it but i cant.
here is the question....
could any one help me. i am making an app, and in the java, numbers are send to a int array and i need to check if any of the numbers in the array repeated and if there are to call a method or something like that. Is there a method to check this or something similar? or would i have to do it using loops and if statements, which i have tried but is getting a bit long and confusing. Any advice would be great, thanks.
int test[] = {0,0,0,0,0,0,0}; (The Array)
(A method to check if any of the arrays numbers are repeated)
First don't make double topic.
Second you are searching for a Java answer not related to Android.
I think that maybe it's better if you first learn java (or other language like).
I would store the items in a Set if you do not want them to repeat. If add returns false then you have a repeating number
Set uniqueItems = new HashSet();
for(int i=0;i<test.length;i++)
if(!uniqueItems.add(test[a]))
System.out.println("The item is already in the set");
First, sort the array. Then search through the array comparing each node to the node on either of it's sides. Or you could store the data in a Set which cannot have duplicates.
Arrays.asList(test).contains(valueYouWantCheck).
If you want to find out for each and every value in test array, Yes I think you need to loop the array.
I keep getting random java.lang.IndexOutOfBoundsException errors on my program.
What am i doing wrong?
The program runs fine, its a really long for loop, but for some elements i seem to be getting that error and then it continues on to the next element and it works fine.
for (int i = 0; i < response.getSegments().getSegmentInfo().size()-1; i++) {
reservedSeats = response.getSegments().getSegmentInfo().get(i).getCabinSummary().getCabinClass().get(i).getAmountOfResSeat();
usedSeats = response.getSegments().getSegmentInfo().get(i).getCabinSummary().getCabinClass().get(i).getAmountOfUsedSeat();
System.out.println("Reserved Seats: " + reservedSeats);
System.out.println("Used Seats : " + usedSeats);
}
How can i prevent this errors?
For those thinking this is an array, it is more likely a list.
Let me guess, you used to be getting ConcurrentModificationExceptions, so you rewrote the loop to use indexed lookup of elements (avoiding the iterator). Congratulations, you fixed the exception, but not the issue.
You are changing your List while this loop is running. Every now and then, you remove an element. Every now and then you look at the last element size()-1. When the order of operations looks like:
(some thread)
remove an element from response.getSegments().getSegmentInfo()
(some possibly other thread)
lookup up the size()-1 element of the above
You access an element that no longer exists, and will raise an IndexOutOfBoundsException.
You need to fix the logic around this List by controlling access to it such that if you need to check all elements, you don't assume the list will be the same as it crosses all elements, or (the much better solution) freeze the list for the loop.
A simple way of doing the latter is to do a copy of the List (but not the list's elements) and iterate over the copy.
--- Edited as the problem dramatically changed in an edit after the above was written ---
You added a lot of extra code, including a few extra list lookups. You are using the same index for all the list lookups, but there is nothing to indicate that all of the lists are the same size.
Also, you probably don't want to skip across elements, odds are you really want to access all of the cabin classes in a segmentInfo, not just the 3rd cabinClass in the 3rd segmentInfo, etc.
You seem to be using i to index into two entirely separate List objects:
response.getSegments().getSegmentInfo().get(i) // indexing into response.getSegments().getSegmentInfo()
.getCabinSummary().getCabinClass().get(i) // indexing into getCabinSummary().getCabinClass()
.getAmountOfResSeat();
This looks wrong to me. Is this supposed to happen this way? And is the list returned by getCabinClass() guaranteed to be at least as long as the one returned by getSegmentInfo()?
You're using i both as an index for the list of segment infos and for the list of cabin classes. This smells like the source of your problem.
I don't know your domain model but I'd expect that we need two different counters here.
Refactored code to show problem (guessed the types, replace with correct class names)
List<SegmentInfo> segmentInfos = response.getSegments().getSegmentInfo();
for (int i = 0; i < segmentInfos.size()-1; i++) {
// use i to get actual segmentInfo
SegmentInfo segmentInfo = segmentInfos.get(i);
List<CabinClass> cabinClasses = segmentInfo.getCabinSummary.getCabinClass();
// use i again to get actual cabin class ???
CabinClass cabinClass = cabinClasses.get(i);
reservedSeats = cabinClass.getAmountOfResSeat();
usedSeats = cabinClass.getAmountOfUsedSeat();
System.out.println("Reserved Seats: " + reservedSeats);
System.out.println("Used Seats : " + usedSeats);
}
Assuming that response.getSegments().getSegmentInfo() always returns an array of the same size, calling .get(i) on it should be safe, given the loop header (but are you aware that you are skipping the last element?) However, are you sure that .getCabinSummary() will return an array that is as large as the getSegmentInfo() array? It looks suspicious that you are using i to perform lookups in two different arrays.
You could split the first line in the loop body into two separate lines (I'm only guessing the type names here):
List<SegmentInfo> segmentInfo = response.getSegments().getSegmentInfo().get(i);
reservedSeats = segmentInfo.getCabinSummary().get(i).getAmountOfResSeat();
Then you'll see which lookup causes the crash.