【问题标题】:ToString does not workToString 不起作用
【发布时间】:2015-04-17 21:25:08
【问题描述】:

为什么 toString 在我的代码中不起作用?输出应该是 idChild[] 中的所有元素。

错误:

子[Ljava.lang.String;@15db9742

public String[] onePointCrossover(int father, int mother) {

    String linha1 = individualID.get(father);       
    idFather = linha1.split(" ");
    String linha2 = individualDep.get(father);  
    depenFather= linha2.split(" "); 
    String linha3 = individualHour.get(father);
    hourFather = linha3.split(" ");

    String linhaA = individualID.get(mother);       
    idMother = linha1.split(" ");
    String linhaB = individualDep.get(mother);  
    depenMother= linha2.split(" "); 
    String linhaC = individualHour.get(mother);
    hourMother = linha3.split(" ");

    String [] idChild = new String [idFather.length];
    int crossPoint = (int) (Math.random()*idFather.length);

    for(int i=0; i<idFather.length; i++)
    {
        if (i<crossPoint)
            idChild[i] = idFather[i];
        else
            idChild [i] = idMother[i];
    }

    System.out.println("child" + idChild.toString());
    return idChild;     
}

【问题讨论】:

  • 如果你想要不同于标准的行为,你必须override toString() 方法。调用 idChild.toString() 只是将对象类型和位置作为字符串提供给您。

标签: tostring


【解决方案1】:

如果您想遍历数组中的所有子元素,则需要遍历它,否则您会尝试将对象数组作为字符串读取!

试试:

foreach (string s in idChild)
    {
         System.out.println(s);
    }

【讨论】:

    【解决方案2】:

    这是toString() 的工作方式(文档here):Object 类(以及所有数组)的默认实现显示类名、@ 符号和哈希的十六进制表示对象代码:

    public String toString() {
        return getClass().getName() + "@" + Integer.toHexString(hashCode());
    }
    

    文档说:

    返回对象的字符串表示形式。通常,toString 方法返回一个“以文本形式表示”该对象的字符串。

    所以真正由程序员来选择“文本表示”的含义。

    如果您想打印数组中所有项目的String 表示,您必须对其进行迭代。

    【讨论】:

      猜你喜欢
      • 2015-12-01
      • 1970-01-01
      • 2015-07-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多