2

我有一组代表数字逻辑门的类,我想创建一个 toString() 命令,它将递归地通过并打印它们。问题是它们可以包含 Gate、Boolean 或 Integer,当我调用 Boolean.toString() 或 Integer.toString() 时,会打印对象 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 + ")");
    }
}
4

1 回答 1

6

您的输出清楚地表明您传递int[]boolean[]进入您的构造函数,而不是IntegerBoolean所说的(参见Class.getName()二进制类型名称的含义,例如[I)。

如果这是预期的,那么您需要提供自己的函数来将数组转换为String并使用它,而不是使用toStirng()为数组返回基于哈希值的默认实现。

于 2012-09-17T17:04:28.227 回答