Java prints an array of objects
•
Java
I know there are many web pages about this problem, but I can't understand it in my case
I need to print an array of objects For example, I have an array of objects to hold the objects in the "shape" class Do I call the toString method for each object in the array, or do I write the toString method in the objectlist to print out the instance variables? If so, what should I do?
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 }
My goal is to print this:
square has 4 sides hexagon has 6 sides
Solution
The easiest way is to use arrays toString:
Arrays.toString(myArray);
This will internally call the toString method for each element in the array
So just override the toString method in the shape class and it should work
To add further, rewrite the toString method in the class and call the Arrays. in the variable list in this class. toString:
public class ObjectList{ private Object[] list = new Object[10]; ............. public String toString(){ return Arrays.toString(list); } }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码