简体   繁体   English

Java打印一个对象数组

[英]Java printing an array of objects

I know there are a lot of pages about this question, but I cannot understand it in my case. 我知道有很多关于这个问题的网页,但在我的案例中我无法理解。

I need to print the array of objects. 我需要打印对象数组。 For example, I have an array of objects that hold objects from the "shape" class. 例如,我有一个对象数组,用于保存“shape”类中的对象。 Do I call the toString method for each object in the array, or do I code the toString method in ObjectList to print out the instance variables? 我是否为数组中的每个对象调用toString方法,还是在ObjectList中编写toString方法来打印出实例变量? If so, how do I do that? 如果是这样,我该怎么做?

public class Shape{
    private String shapeName;
    private int numSides;

    public String toString(){
        return shapeName + " has " + numSides + " sides.";
    }
}

public class ObjectList{
    private Object[] list = new Object[10];
    private int numElement = 0;

    public void add(Object next){
        list[numElement] = next;
    }

    public String toString(){
        // prints out the array of objects 

        // do I call the toString() method from the object?

        // or do I print the instance variables? What am I printing?

        // I'm guessing I do a for loop here
    }
}

public class Driver{
    public static void main(String[] args){
        ObjectList list = new ObjectList();
        Shape square = new Shape("square", 4);
        Shape hex = new Shape("hexagon", 6);
        list.add(square);
        list.toString();  // prints out array of objects
}

I am aiming for it to print this: 我的目标是打印这个:

square has 4 sides
hexagon has 6 sides

The simplest way to do this is use Arrays.toString: 最简单的方法是使用Arrays.toString:

Arrays.toString(myArray);

This will internally call the toString method of every element of your array. 这将在内部调用数组中每个元素的toString方法。

So just override toString method in your Shape class and it should work fine. 所以只需在Shape类中覆盖toString方法,它应该可以正常工作。

To add further, override toString method in your class where you call Arrays.toString on your variable list : 要进一步添加,请在类中重写toString方法,在该类中调用变量list Arrays.toString

public class ObjectList{
    private Object[] list = new Object[10];
    .............

    public String toString(){
         return Arrays.toString(list);
    }
}

You can do this with bellowed code, make for loop in toString method to print each shape object. 您可以使用下面的代码执行此操作,在toString方法中进行循环以打印每个形状对象。

class Shape{
    private String shapeName;
    private int numSides;

    Shape(String shapeName, int numSides){
        this.shapeName = shapeName;
        this.numSides = numSides;
    }
    public String toString(){
        return shapeName + " has " + numSides + " sides.";
    }
}

class ObjectList{
    private Object[] list = new Object[10];
    private int numElement = 0;

    public void add(Object next){
        list[numElement] = next;
        numElement++;
    }

    @Override
    public String toString(){
        String str="";
        int i=0;
        while(list[i] != null){
            str += list[i]+"\n";
            i++;
        }
        return str;
    }
}

public class Driver{
    public static void main(String[] args){
        ObjectList list = new ObjectList();
        Shape square = new Shape("square", 4);
        Shape hex = new Shape("hexagon", 6);
        list.add(hex);
        list.add(square);
        System.out.println(list);
    }
}

Write a for-each statement in toString() of Object List and create a large String with '\\n' characters and return it as a String . 在Object List的toString()中编写for-each语句,并创建一个带有'\\ n'字符的大型String,并将其作为String返回。 Or may be name displayListElement() will be semantically more correct in which you can simple print all the Objects in the list . 或者可以是名称displayListElement()在语义上更正确,您可以在其中简单地打印列表中的所有对象。

Indeed, you should call toString method for each of objects that you want to print and join them together. 实际上,您应该为要打印的每个对象调用toString方法并将它们连接在一起。 You can use StringBuilder to hold the string-in-the-making as follows: 您可以使用StringBuilder来保存正在进行的字符串,如下所示:

public String toString() {
    StringBuilder result = new StringBuilder();
    for (int i = 0; i <= numElements; i++) {
        result.append(list.toString() + "\n");
    }

    return result.toString();
}

Note that you need to increase numElements (eg numElements++ ) for each add operation as what pbabcdefp said in the comments. 请注意,您需要为每个add操作增加numElements (例如numElements++ ),就像pbabcdefp在评论中所说的那样。 Also, you can use ArrayList class to manage "growing arrays". 此外,您可以使用ArrayList类来管理“增长的数组”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM