有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何使用具有多个参数的dataclass toString?

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


共 (1) 个答案

  1. # 1 楼答案

    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的返回类型。 类似的内容适用于您的items 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