Java 如何在toString()方法中打印数组?

Java 如何在toString()方法中打印数组?,java,arrays,tostring,Java,Arrays,Tostring,我试图通过toString打印一个数组,这样我就可以将它调用到另一个方法。我到底做错了什么?为什么不进行编译,还有什么更好的解决方案 public class Applicants { private String applicant[]; public Applicants() { Application student1 = new Application() Application student2 = new Application() Appli

我试图通过toString打印一个数组,这样我就可以将它调用到另一个方法。我到底做错了什么?为什么不进行编译,还有什么更好的解决方案

public class Applicants
{
    private String applicant[];
    public Applicants()
{
    Application student1 = new Application()
    Application student2 = new Application()
    Application student3 = new Application()
    Application student4 = new Application()
    Application student5 = new Application()
    Application student6 = new Application();

    Application applicant[] = new Application[5];
    applicant[0] = student1;
    applicant[1] = student2;
    applicant[2] = student3;
    applicant[3] = student4;
    applicant[4] = student5;
    applicant[5] = student6;

    for (int index = 0; index < applicant.length; index++)
    {   
         System.out.println(applicant[index]);
    }

}
public String toString(String[] applicant)
{
    String output = new String();
    String total;
    for (int index = 0; index < applicant.length; index++)
    {
        total = System.out.println(applicant[index]);
    }
    return total;
}
}有三件事不对,一件是嘿,注意

您正在构造函数内部跟踪您的现场申请人。这意味着当您使用构造函数时,字符串[]为空。不是空的,只是空的

您可能想做的是将私有应用程序[]申请人声明为字段,而不是在构造函数中重新声明它

总计=系统输出打印申请者[索引];不是有效的语句。不能将void方法的结果指定给任何对象。你在构造器中就有它,所以很奇怪你在这里没有得到正确的结果

toString不接受任何参数。使用你的领域

请在应用程序对象上定义toString,因为这将使您的生活更轻松。否则,从该对象中提取有意义的信息。在这两种情况下,您都要对这一个进行一些字符串连接,这是留给读者的练习


您需要在应用程序类中声明toString方法:

public class Application {

    @Override
    public String toString() {
       // your code here
    }
 }
请注意替代注释的使用。这将使编译器检查您是否实际重写了您所说的方法-在您当前的代码中,您不是,因为toString不接受任何参数

至于toString的实现,我会选择Google Guava

@Override
public String toString() {
    return MoreObjects.toStringHelper(this.getClass()).add(..).add(..).toString();
 }
有关更多信息,请参见此处:


考虑使用StrugBu建器。它无法编译,因为这几乎是无效代码:total=System.out.printlnapplication[index];您正在使用完全不同的类型跟踪字段变量申请者…这太尴尬了。您是否要覆盖toString?要做到这一点,它们需要有相同的参数。当某些东西没有编译时,编译器会提示您哪些行的代码是错误的。如果不提供这些信息,您就是在要求其他人用比您可用的信息更少的信息来调试您的代码。你认为这公平合理吗?