【发布时间】:2019-08-07 11:47:16
【问题描述】:
我对 Java 比较陌生。我正在练习一个练习,我们探索子类和超类实例的多态行为。本练习建立在抽象类和接口的概念之上。 本练习中介绍了 ArrayList。 其中一个问题要求我们创建一个名为 products 的 WrittenWork 对象的 ArrayList,并将适当的对象添加到 ArrayList。
我的问题是 ArrayList 一直打印第一个项目 3 次,然后打印其余项目。
有人能解释一下为什么会这样吗?
编辑:感谢你们,我意识到我犯的错误! 我从
更改了 for 循环 for(WrittenWork w: products)
System.out.println(w1.toString());
System.out.println(w2.toString());
System.out.println(w3.toString());
到
for(WrittenWork w: products)
System.out.println(w.toString());
This Image shows how all the classes are connected
代码如下:
import java.util.*;
public class BookStore
{
public static void main(String[] args)
{
Author a1 = new Author("Malcom Gladwell");
Author a2 = new Author("Steven Johnson");
Author a3 = new Author("Mathias Johansson");
Author a4 = new Author("Evan Ackerman");
Author a5 = new Author("Erico Guizzo");
Author a6 = new Author("Fan Shi");
WrittenWork w1 = new Novel(a1, "What the Dog Saw and other adventures", 503);
WrittenWork w2 = new Novel(a2, "How We Got to Now: Six Innovations That Made the Modern World", 320);
WrittenWork w3 = new Novel(a2, "Everything Bad Is Good For you: How Today's Popular Culture is Actually Making us Smarter", 254);
ArrayList<WrittenWork>products = new ArrayList<>();
products.add(w1);
products.add(w2);
products.add(w3);
for(WrittenWork w: products)
System.out.println(w1.toString());
System.out.println(w2.toString());
System.out.println(w3.toString());
}
}
【问题讨论】:
-
你的循环没有括号,所以只执行第一条语句。如果您对打印语句进行硬编码,为什么还要使用循环?
-
为什么不打印 w?