I am adding some values dynamically to an arraylist and comparing the values stored in the list with the previous values.mWhlw doing this I am getting the following exception "java.lang.IndexOutOfBoundsException: Index: 2, Size: 2".
Hers is the code snippet:
Kindly look into this issue and please let me know if anyone has any idea.
Yes, although I'm not sure your logic is correct.
1. You are comparing only adjacent object. Are you sure this is what you want ? I mean, if there are 3 objects, the object at index 0 won't be compared to the object at index 2.
2. You're not comparing strings, are you ? Otherwise using "==" would be a bad idea.
I actually want to compare all the previous elements. not the adjacent elements. I guess My logic is wrong. could you please tell me how could change my code to compare element in a list with all previous element.
for eg.i f there are 3 objects,how can i compare the object at index 0 to the object at index 2.
Yes i am comparing two strings, so i will use equals method for the same.
To compare an object in a list with all other objects in the same list, you must use a nested for-loop within your existing for-loop - the inner for-loop defined the same way as the outer(for 1 to size-1 step 1).
So...., whats the objective of this piece of code? - like, you want to detect when a duplicate String is being added to your arraylist or something?
I'm not sure what your requirement is, but...but if so, you can go for a Set instead of an ArrayList.
The main objective of my code is to compare the elements in the list, and if the same element exists in the list then do some action else do some other action. could you please share some code snippet that could help me.
Hey, I'm supposed to be the guide! Wait up! No fair! You have the tiny ad!