ListDemo(通过List接口的实现类ArrayList实现)
ListDemo(通过List接口的实现类ArrayList实现需求)
元素个数不确定
要求获得元素的实际个数
按照存储顺序获取并打印元素信息
package
com1018;
import
java.util.ArrayList;
import
java.util.Iterator;
import
java.util.List;
/**
*
*
@author a496006
* store many Penguin info, get Penguin info, print out each penguin's info
*/
public
class CollectionDemo {
publicstaticvoid main(String[] args) {
Penguin
p1 = new Penguin("dajiao", "male");
Penguin
p2 = new Penguin("qq", "female");
List<Penguin>
list = new ArrayList<>();
list.add(p1);
list.add(p2);
System.
out.println("total" + " " + list.size() + " " + "penguins");
for (Penguin obj : list) {
System.
out.println(obj.getName() + "\t" + obj.getGender());
}
Iterator<Penguin>
it = list.iterator();
System.
out.println("total" + " " + list.size() + " " + "penguins");
while (it.hasNext()) {
Penguin
p = it.next();
System.
out.println(p.getName() + "\t" + p.getGender());
}
}
}
package
com1018;
public
class Penguin {
private String name;
private String gender;
public Penguin(String name, String gender) {
this.name = name;
this.gender = gender;
//System.out.println("running this constructor");
}
public String getName() {
returnname;
}
publicvoid setName(String name) {
this.name = name;
}
public String getGender() {
returngender;
}
publicvoid setGender(String gender) {
this.gender = gender;
}
}