I need your help with some sample code for a situation I could not get free from.
I have a simple list of objects. My class is like this:
class MyClass {
String str;
Integer intgr;
}
And the list contains elements like:
[{a1 5}, {b2 3}, {g1 1}, {b5 1}, {c9 11}, {g2 3}, {d1 4}, {b3 19}... ... ...]
I need to check if any element contain the same prefix in string (here suffix is the last single character) then keep that element which have greater value in integer. The expected output from the above example list will be:
[{a1 5}, {c9 11}, {g2 3}, {d1 4}, {b3 19}... ... ...]
Strings will have unique values but could have matches in prefix. I’m not that good in java. So can anybody help me out from this? Here is the code I’m trying but getting IndexOutOfBoundsException. This code has faults, so need some help from you.
Thanks!
int size = list.size();
for (int j = 0; j < size; j++) {
if (list.get(j).str.substring(0, list.get(j).str.length()-1).compareTo(list.get(j+1).str.substring(0, list.get(j+1).str.length()-1)) == 0) {
if (list.get(j).intgr > list.get(j+1).intgr)
list.remove(list.get(j+1));
size--;
else {
list.remove(list.get(j));
j--;
size--;
}
}
}
There are two problems with your code. First, when
j == size - 1(the last iteration), you are calling list.get(j+1), which is what is causing the exception. Just change your loop condition toj < size - 1and the exception should go away. (Alternatively, start atj = 1and compare to the previous element.)Second, you are only comparing each element with its immediate successor element. From your description, it doesn’t sound like that’s what you want to do.
I’d suggest capturing the logic of comparison in a separate method. It might be part of
MyClass:(This can easily be transformed into a method with two arguments that would be outside
MyClass.) Then you can use the method to decide what to keep. You need to do a double iteration to find non-adjacent objects: