Reputation: 9
I want to create a loop that iterates through an ArrayList of objects.
for (int i = 0, k=i+1; k < arr.size(); i++) {
int tprice;
tprice=0;
if (arr.get(i).getID()=arr.get(i+1).getID()) {
tprice = arr.get(i).getPrice() + arr.get(i+1).getPrice();
}
else {
if (tprice!=0) {
System.out.println(tprice);
}
else {
System.out.println(arr.get(i).getDuration());
}
}
}
I want to compare element i
to element i+1
of the ArrayList, without creating a nested for loop as I am not interested in all the permutations. (e.g, 1->2
then 2->3
, not 1->2
then 1->3
)
However, my line of code always causes an error because index k
at the end of the loop is referencing an out-of-bounds index (or the equivalent for ArrayList).
Say i have three arrays : i=0 compares to i=1, i=1 compares to i=2, i=2 compares to i=3 but throws back an error since it doesn't exist.
Is there any way to overcome this? It seems silly, but I couldn't find anything about it across the forums.
exemple hardcode:
arr.add(new object(444,24)) // 444 is ID, 24 is Price
arr.add(new object(444,29)) // 444 is ID, 29 is Price
arr.add(new object(121,33)) // ...
wanted outcome :
53
53
33
side-question : if i am dealing with the same ID, i would ideally wish to print only once. Is there anyway to do so?
Upvotes: 1
Views: 1972
Reputation: 7828
If all you want to check is the adjacent
elements in the array, just start from the index 1
till the end and compare the adjacent: current
and previous
.
for (int i = 1; i < arr.size(); ++i) {
if (arr.get(i) > arr.get(i-1)) ....
}
Upvotes: -1
Reputation: 44398
If you touch the two consequent elements of the array, you have to stop one element before you read the end:
for (int i = 0; i < arrayList.size() - 1; i++) {
// do stuff with arrayList.get(i) and arrayList(i+1)
}
Of course, the arrayList must contain at least two elements otherwise the loop will never be entered since the arrayList.size() - 1
would be equal to 0
.
Moreover, you confuse arrays with ArrayList<T>
.
List<T>
of size list.size()
has methods list.add(T t)
and list.get(int index)
.int[] array
of size (length) array.length
access to items with index array[0]
.Upvotes: 1