- 因为Collection是借口,所以由他的子类去实现,在这里用的是ArrayList方法
正文代码演示
package Collection;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
public class Test1 {
public static void main(String[] args) {
Collection collection = new ArrayList();
collection.add("路飞");
collection.add("乌塔");
collection.add("香克斯");
System.out.println(collection.size());
System.out.println(collection);
collection.remove("香克斯");
System.out.println(collection.size());
for (Object o : collection) {
System.out.println(o);
}
System.out.println("-----------iterator迭代器----------------");
Iterator iterator = collection.iterator();
while(iterator.hasNext()){
String next = (String)iterator.next();
System.out.println(next);
}
System.out.println(collection.contains("香克斯"));
System.out.println(collection.contains("路飞"));
}
}
package Collection;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
public class Test2 {
public static void main(String[] args) {
Collection collection = new ArrayList();
Student s1 = new Student("路飞", 19);
Student s2 = new Student("索隆",19);
Student s3 = new Student("山治",19);
collection.add(s1);
collection.add(s2);
collection.add(s3);
System.out.println(collection.size());
System.out.println(collection.toString());
collection.remove(s3);
System.out.println(collection.size());
for (Object o : collection) {
System.out.println(o);
}
System.out.println("-------------iterator-------------------");
Iterator iterator = collection.iterator();
while(iterator.hasNext()){
Student next = (Student) iterator.next();
System.out.println(next);
}
System.out.println(collection.contains(s3));
System.out.println(collection.contains(s1));
}
}
class Student{
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
感谢观看