Integer或Boolean的toString(),不返回Object ID

时间:2012-09-17 16:58:37

标签: java object tostring

我有一组表示数字逻辑门的类,我想创建一个toString()命令,它将以递归方式通过并打印它们。问题是它们可以包含Gate,Boolean或Integer,当我调用Boolean.toString()或Integer.toString()时,将打印Object ID而不是指定的值。有没有办法在这些对象上一般调用toString()(或类似的)命令并让它们打印指定的值?

使用下面的代码,输出看起来像:“AND([I @ 6ca1c,[Z @ 1bf216a]”

我希望它看起来像:“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 + ")");
    }
}

1 个答案:

答案 0 :(得分:6)

您的输出明确表示您已将int[]boolean[]传递到构造函数中,而不是IntegerBoolean,如您所说(请参阅Class.getName()了解其含义二进制类型名称,例如[I)。

如果是预期的,则需要提供自己的函数将数组转换为String,并使用默认的toStirng()实现来返回基于散列的数组值。