In searching a pre-populated ArrayList, call it
List<String> myList= new ArrayList<String>();
I am trying to add new elements to it based on these elements containing certain regex values. I am having success when I just need to return one substring of the element. For example, if I have
String removable = "X";
which resides in an element, call it
ABCDX
the X is easily removed and added to the ArrayList with the code
if(myList.get(i).length() == 5 && myList.get(i).substring(4,5).contains(removable))
{
myList.add(i+1, myList.get(i).substring(0, 4));
}
but when I have an element such as
ABXCD ,
which I presumed could be handled with
if(myList.get(i).length() == 5 && myList.get(i).substring(2,3).contains(removable))
{
myList.add(i+1, myList.get(i).substring(0, 2).substring(3, 5));
}
I get a String Index Out of Bounds Exception. How can this be rectified?
In your second code example you are using
should this not be
Edit
I believe your problem is that you are substring’ing a substring. Your code does this
So what that is saying is, get the substring of a string, then get a substring of the previously retrieved substring. Since the first substring is only 2 characters long, the second substring returns out of bounds as you are trying to start from index 3 which does not exist.
Your code pretty much evaluates to:
You need to do something like
or find an alternative method of doing what you want.