在 ArrayList 中执行命令

通常,我会执行以下操作:


System.out.println("Title DVD 1: " + dvd1.getTitle());

System.out.println("Title DVD 2: " + dvd2.getTitle());

然后我会得到 DVD 1 和 DVD 2 的标题。如果我想打印 100 个 DVD 标题,显然我需要很多


System.out.println.

我设法在 ArrayList 中获取这些System.out.println,如下所示:


ArrayList<String> displayDVDList = new ArrayList<String>();


for ( int i = 0; i <= 22; i++) {

    displayDVDList.add("System.out.println(\"Title DVD " + i + " : \" 

        + dvd" + i + ".getTitle());");

    System.out.println(displayDVDList.get(i) + " ");

}

但是,我无法执行那些System.out.println来显示标题。因此,如何执行恰好是System.out.println命令的 ArrayList 的值?


任何帮助深表感谢。谢谢你。


幕布斯6054654
浏览 150回答 3
3回答

慕标琳琳

假设dvd1and的类型是带有该方法dvd2的类,您的代码可能如下所示,其中列表的元素不是值,而是对象。DvdgetTitle()StringDvd// Build list of DVDsRandom random = new Random();ArrayList<Dvd> displayDVDList = new ArrayList<>();for (int i = 0; i <= 22; i++) {&nbsp; &nbsp; String dvdTitle = "DVD #" + (random.nextInt(1000) + 1);&nbsp; &nbsp; displayDVDList.add(new Dvd(dvdTitle));}// Print list of DVDsfor (int i = 0; i < displayDVDList.size(); i++) {&nbsp; &nbsp; Dvd dvd = displayDVDList.get(i);&nbsp; &nbsp; System.out.println("Title DVD " + (i + 1) + ": " + dvd.getTitle());}

心有法竹

每个答案都有帮助,我正在添加它。首先要了解的是,您希望打印对象的某些属性。使用对象类中的 toString() 方法,因为它是专门为它创建的。在您的班级中使用 arrayList.toString() 并覆盖 toString() 。class Person1{&nbsp; &nbsp; String name ;&nbsp; &nbsp; String state;&nbsp; &nbsp; public Person1(String name, String state) {&nbsp; &nbsp; &nbsp; &nbsp; super();&nbsp; &nbsp; &nbsp; &nbsp; this.name = name;&nbsp; &nbsp; &nbsp; &nbsp; this.state = state;&nbsp; &nbsp; }&nbsp; &nbsp; public Person1() {&nbsp; &nbsp; &nbsp; &nbsp; super();&nbsp; &nbsp; }&nbsp; &nbsp; @Override&nbsp; &nbsp; public String toString() {&nbsp; &nbsp; &nbsp; &nbsp; return "Person [name=" + name + ", state=" + state + "]";&nbsp; &nbsp; }}public static void main(String[] args) {&nbsp; &nbsp; &nbsp; &nbsp; Person nitin = new Person("nitin", "delhi");&nbsp; &nbsp; &nbsp; &nbsp; Person chandan = new Person("chandan", "delhi");&nbsp; &nbsp; &nbsp; &nbsp; Person anshu = new Person("anshu", "bihar");&nbsp; &nbsp; &nbsp; &nbsp; Person rahul = new Person("rahul", "bihar");&nbsp; &nbsp; &nbsp; &nbsp; Person amar = new Person("nitin", "UP");&nbsp; &nbsp; List<Person> peoples = Arrays.asList(nitin,chandan, anshu, rahul,amar);&nbsp; &nbsp; System.out.println(peoples);&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; }

白衣非少年

您可以先加载所有内容,然后使用 System.out.println 进行打印。Java 8 有一种使用流运行的方法。例如:ArrayList<String> displayDVDList = new ArrayList<String>();displayDVDList.add("Title 1");displayDVDList.add("Title 2");displayDVDList.add("Title 3");displayDVDList.add("Title 4");displayDVDList.add("Title 5");displayDVDList.forEach(System.out::println);我希望它对你有帮助!
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java