如何在 Java 中编写一种方法, 它可以在数组中打印对象?
示例
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]+"
"; 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); } }
广告