【发布时间】:2016-08-25 17:59:03
【问题描述】:
我理解 toString() 方法,当调用外部方法时,它们必须是返回类型。
下面的评论块描述了我正在尝试做的事情。
以后当我与 setter 和 getter 一起工作时,这些知识肯定会非常宝贵。
import java.util.*;
public class Display_ArrayList {
static ArrayList<String> cars = new ArrayList<String>();
public static void main(String[] args) {
cars.add("Nissan Maxima");
cars.add("Toyota Prius");
cars.add("Renault Clio");
cars.add("Ford Focus");
cars.add("Volkwagen Passat");
System.out.println("");
System.out.println("[Standard toString()]:");
System.out.println(cars.toString());
System.out.println("");
System.out.println("[Custom toString()]:");
System.out.println(custom_cars_toString());
}
// Array list displays the car list all on the same line
public static String getCarList() {
return cars.toString();
}
// *************************************************************************
// I want Array list contents to be displayed on their own lines without
// commas or brackets, while at the same allowing this method to be
// retrieved by a toString() method
// *************************************************************************
// public static void getCarList() {
// for (String element : cars)
// System.out.println(element);
// }
public static String custom_cars_toString() {
return "The cars contained are: \n" + getCarList();
}
}
【问题讨论】:
标签: arrays list tostring lines