我如何 return/implement ArrayList 的 toString?另外,只想检查我是否正确创建了我的对象?

How do I return/implement the toString for the ArrayList? Also, just want to check that I've correctly created my objects?

import java.util.ArrayList;
import java.util.Date;
import javafx.scene.shape.Circle;

public class List2 {
    public static void main(String[] args){
        Loan newLoan = new Loan();                  
        Date theDate = new java.util.Date();
        Circle newCircle = new Circle();
        String s = new String();
        //last semicolon is also an error?

        private ArrayList<Object> List = new ArrayList<Object>();

        List.add(newLoan);
        List.add(theDate);
        List.add(newCircle);
        List.add(s);

        //**There's an error underlining all my . and ; when I add them to the List above?

        public String toString() {
            String results = "";
            for (Object d : List) {
                results += "," + d.toString();
            }
        }
    }
//I'm pretty new to this stuff

你的代码有很多错误:

第一 永远不要以大写字母开头命名变量,java 使用驼峰式

第二 不要在方法中使用 private public 声明变量。

private ArrayList<Object> List = new ArrayList<Object>();

第三 您不能在另一个方法中声明一个方法,您必须在完成后关闭第一个方法:

public static void main(String args[]){//------Start
  ...
}//---End

public String toString(){//---Start
  ...
}//---End

当你想调用带有参数的方法时,你可以像这样传递它们:

method(list);

第五名 ArrayList 已经实现了 toString 所以你不需要再次创建它,你可以使用 :

list.toString()

如果你想再次实现它,你可以使用:

public static void main(String[] args) {
    King newLoan = new King();
    Date theDate = new java.util.Date();
    Circle newCircle = new Circle();
    String s = new String();

    ArrayList<Object> list = new ArrayList<Object>();

    list.add(newLoan);

    list.add(theDate);

    list.add(newCircle);

    list.add(s);

    System.out.println(newLoan.toString(list));
}

public String toString(ArrayList<Object> list) {
    String results = "";
    for (Object d : list) {
        results += "," + d.toString();
    }
    return results;
}

第一件事...

您的代码未编译,因为您违反了 sintax 规则...

这里是:

private ArrayList<Object> List = new ArrayList<Object>();

无法声明为 private 因为你在方法内部,那是无效的,

因为 List 在静态上下文中使用,所以它也必须声明为 Static,或者创建 class List2[=31 的对象=]

另一方面

toString 方法 returns 一个字符串对象,你需要 return 一些东西,比如 results object I can infer.