1
ArrayList<Items> itemsClass = new ArrayList<Items>();

itemClass.add(new Items(String, int, boolean));

public class Items{

    String x;
    int y;
    boolean z;

    public Items(String x, int y, boolean z){
        x = this.x;
        y = this.y;
        z = this.z;
    }

    public toString(){

        /*
         *This is my question
        */

    }

}

如何在此类中使用构造函数编写 toString 方法,以便可以添加到我的 ArrayList?

4

1 回答 1

3

toString 方法与添加到 ArrayList 无关。toString 方法将用于以您想要的方式打印出对象。如果你写

// Instantiate the itemsClass
ArrayList itemsClass = new ArrayList();

// Add multiple Items to the itemClass
itemClass.add(new Items("String1", 0, true));
itemClass.add(new Items("String2", 1, true));

// Uses the individual itemClasses toString methods
System.out.println(itemClass[0]);
System.out.println(itemClass[1]);

您缺少 toString 的返回类型。像这样的东西适用于您的项目 toString:

public String toString(){
   string result = "";
   result += "String: " + x + "\n";
   result += "Integer: " + y + "\n";
   result += "Boolean: " + z + "\n";
   return result;
}

这将产生如下输出:

String:  String1
Integer: true
Boolean: 1

String: String2
Integer: true
Boolean: 1
于 2013-04-02T02:29:16.410 回答