I have to trim (including whitespaces within the string) all the strings in a list. I have written a method to do this trim using regex. I am using strArray[i] = trimString(strArray[i]); instead of using an enhanced for loop. I assume since string is immutable this way of assigning back to the same array element is correct. Am I right?
public void trimStringArray(String[] strArray){
if(strArray!= null && strArray.length > 0){
for(int i=0;i<strArray.length;i++){
strArray[i] = trimString(strArray[i]);
}
}
}
Yes, that’s fine, and you wouldn’t be able to use the enhanced for loop. However, you can simplify your code by getting rid of the
length > 0check – there’s no harm in it executing the loop 0 times… and personally I would usually expect the parameter to such a method to be non-null anyway, leading to code like this:(
Preconditions.checkNotNullcomes from Guava in this case.)You could leave it accepting
null– but do you really have many situations where it’s valid to have a null array, but you want to trim everything if it’s not?As a readability thing, I’d also encourage you to include a bit more whitespace – it’s definitely a personal preference, but I know I find code with no spaces, such as this, harder to read: