views:

62

answers:

3

Here's where I wish Java's String class had a replaceLast method, bu it doesn't and I'm getting the wrong results with my code.

I'm writing a program that searches a data structure for any items that match a string prefix. However, since I'm using an Iterator, the last item returned by the iter.next() call doesn't match the pattern, so I want to change the search string so that the last character of the query is increased by one letter. My testing code is returning [C@b82368 with this code and An as titleSearch:

public String changeLastCharacter(String titleSearch) {
    char[] temp= titleSearch.toCharArray();

    char lastLetter= temp[temp.length-1];
    lastLetter++;
    temp[temp.length-1]= lastLetter;

    String newTitleSearch= temp.toString();
    return newTitleSearch;
}

First, what is the cause of the output from this code? Second, is there a better way to execute my solution?

+3  A: 

You want:

newTitleSearch = new String(temp);

The toString method is not overridden for arrays; it's the usual Object.toString, intended for debugging. The above actually creates a string of the characters. An alternative is:

int len = titleSearch.length();
String allButLast = titleSearch.substring(0, len - 1);
newTitleSearch = allButLast + (titleSearch.charAt(len - 1) + 1);
Matthew Flaschen
I figured it was something like this. I was following an example and mixed up the last line of code. Time for me to call it a day now.
Jason
Nit-pick: *"The character array toString method is similar to the default ..."*. Actually, it >>is<< the default; i.e. `Object.toString()`.
Stephen C
@Stephen, thanks, I forgot the array specifier ("[C") was just the class name.
Matthew Flaschen
+1  A: 

Your problem is temp.toString(). Try String newTitleSearch = new String(temp); instead.

I figured this out by System.out.println(temp[0]+","+temp[1]); after temp[1] add been assigned to the incremented value. You could do this even easier by using your IDE's debugger.

Since the array was being assigned properly, the problem had to be in the toString().

Tony Ennis
+2  A: 

Whenever you see unexpected output like ....@<hex-digits>, the chances are that you are accidentally using toString() on some object whose class inherits the default implementation from Object.

The default toString() method returns a String whose value consists of the type name for the object combined with the object's "identity hash code" as hex digits. In your case the [C part is the type name for a char[] object. The '[' means "array of" and the 'C' means the char primitive type.

The rules for forming the type names used in the default toString() method are fully documented in the javadocs for java.lang.Class.getName().

Stephen C
Thanks for the clarification. I don't use toString all that much, so was unfamiliar with the unexpected output. You really do learn something new every day.
Jason