public class working {
public static String str = "123zASdcvb/;[";
public static void main(String[] args){
System.out.println("!!!"+new LetterInventory(str));
}
public static class LetterInventory {
public char[] arr;
public LetterInventory(String str){
//Strips our string of all non alphabetic garbage
//and assigns it. This regex removes all non a-z
//without regard for case of alphabet (?!).
this.arr = str.replaceAll("[^a-z]", "").toLowerCase().toCharArray();
Arrays.sort(this.arr); //I want to have it sorted to make my life easier.
System.out.printf("Our freshly sorted LI is : %s\n",this.toString());
}
//Simple enough.
public String toString() {
return this.arr.toString();
}
}
}
output:
Our freshly sorted LI is : [C@6d69c9a2
!!![C@6d69c9a2
What is going wrong here? I walked through my debugger and my array does exactly what I want, it is created, cleaned, and sorted just fine. But everytime I try to print my char[].toString() it comes out screwey. Why so?
You're calling toString()
on an array - arrays don't override toString()
, so you end up with the implementation from Object
:
The
toString
method for classObject
returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:getClass().getName() + '@' + Integer.toHexString(hashCode())
As you're dealing with a char[]
, you should just use the String
constructor to create a new string:
return new String(arr);
In other cases you might want to call one of the Arrays.toString
overloads, to get a comma-separated representation.
It's not clear why you're doing any of this in a constructor yourself, by the way. Your program would be simpler with just a main
method:
// Renamed class to follow Java naming conventions
public class Demo {
public static void main(String[] args) {
String input = "123zASdcvb/;[";
char[] chars = str.replaceAll("[^a-z]", "").toLowerCase().toCharArray();
Arrays.sort(chars);
System.out.printf("Our freshly sorted LI is : %s\n", new String(chars));
}
}
See more on this question at Stackoverflow