Search code examples
javaobjecttostring

toString() of Integer or Boolean without returning Object ID


I have a set of classes which represent digital logic gates, and I would like to create a toString() command which will recursively go through and print them. The problem is that they can contain a Gate, Boolean, or Integer, and when I call Boolean.toString() or Integer.toString(), the Object ID is printed rather than the assigned value. Is there a way to generically call a toString() (or similar) command on these objects and have them print the assigned value?

With the code below, the output looks something like: "AND([I@6ca1c,[Z@1bf216a)"

I would like it to look like: "AND(11,true)"

public static class Gate{
    public Object in1;
}

public static class ANDgate extends Gate{

    public Object in2;

    public ANDgate(Object first,Object second){
        in1 = first; // these can be Integer, Boolean, or another Gate
        in2 = second;
    }
    public String toString(){
        return("AND(" + in1 + "," + in2 + ")");
    }
}

public static class NOTgate extends Gate{

    public NOTgate(Object obj){
        in1 = obj; // this can be Integer, Boolean, or another Gate

    }
    public String toString(){
        return("NOT(" + in1 + ")");
    }
}

Solution

  • Your output clearly says that you pass int[] and boolean[] into your constructor, not Integer and Boolean as you say (see Class.getName() for the meaning of binary type names such as [I).

    If it's expected, than you need to provide your own function to convert arrays to String and use it instead on using the default toString() implementation that return hash-based values for arrays.