Wednesday, September 07, 2011

Very simple Java puzzle


I spent a good minute figuring out what was going on. See if you like solving this one:

The piece of code I will be showing in a second receives a String that might have a single digit at the end. I need to extract that digit and increment by one. If you wondered, the code is actually a content automation tool that runs inside the Apache Jackrabbit (it's actually Adobe Day CQ/CRX) and it's messing with the content nodes and their attributes. Sibling nodes have unique names and CQ simply adds the _x, where x increments with every new node of the same original name. My script needs to do the same and so I am looking at an existing node and trying to parse out it's "x" to further increment it. It goes like this:

if (Character.isDigit(nodeName.charAt(nodeName.length() - 1))) {
    colNumber = Math.max(colNumber , Integer.valueOf(nodeName.charAt(nodeName.length() - 1)) + 1);
} else {
    colNumber++;
}

and for a nodeName of colctrl_1 is says the next number is ... 50.

if I do like this:

if (Character.isDigit(nodeName.charAt(nodeName.length() - 1))) {
    colNumber = Math.max(colNumber , Integer.parseInt(nodeName.charAt(nodeName.length() - 1)) + 1);
} else {
    colNumber++;
}

I will get a compilation error because there's not parseInt(char). so I change it to look like this:

if (Character.isDigit(nodeName.charAt(nodeName.length() - 1))) {
    colNumber = Math.max(colNumber , Integer.parseInt("" + nodeName.charAt(nodeName.length() - 1)) + 1);
} else {
    colNumber++;
}

now it reports the next number is 2.

I am sure you know why, I now do too. Still, will you tell me?

p.s. Here's a nice read from Alex Miller on the Integer.valueOf(): http://tech.puredanger.com/2007/02/01/valueof

2 comments:

max said...

Fun :)

int num = Character.getNumericValue(nodeName.charAt(nodeName.length() - 1));

It can do the transformation in more elegant way, at least from my view :)

Pavel Veller said...

yep. it could have at least given me a warning. There's no valueOf(char), there is, however, the valueOf(int). No autoboxing can solve the inherent problem of primitives not being first class objects. This implicit conversion follows its own rules