Java 打印对象数组 [英] Java printing an array of objects

查看:113
本文介绍了Java 打印对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道有很多关于这个问题的页面,但在我的情况下我无法理解.

I know there are a lot of pages about this question, but I cannot understand it in my case.

我需要打印对象数组.例如,我有一个对象数组,其中包含来自形状"类的对象.我是为数组中的每个对象调用 toString 方法,还是在 ObjectList 中编写 toString 方法以打印出实例变量?如果是这样,我该怎么做?

I need to print the array of objects. For example, I have an array of objects that hold objects from the "shape" class. 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? 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
}

我的目标是打印这个:

square has 4 sides
hexagon has 6 sides

推荐答案

最简单的方法是使用 Arrays.toString:

The simplest way to do this is use Arrays.toString:

Arrays.toString(myArray);

这将在内部调用数组中每个元素的 toString 方法.

This will internally call the toString method of every element of your array.

所以只需覆盖 Shape 类中的 toString 方法,它应该可以正常工作.

So just override toString method in your Shape class and it should work fine.

要进一步添加,请在您的类中覆盖 toString 方法,在您的变量 list 上调用 Arrays.toString :

To add further, override toString method in your class where you call Arrays.toString on your variable list :

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

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

这篇关于Java 打印对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆