1.创建Student类
package com.yundait.Demo01;
/**
*
*学生类
* @author zhang
*/
public class Student {
private String name;
private int age;
public Student() {
}
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 +
'}';
}
}
2.创建CollectionDemo02类,实例化Student对象,演示如何在集合中添加、删除、清空、遍历、判断。
package com.yundait.Demo01;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
public class CollectionDemo02 {
public static void main(String[] args) {
//新建Collection对象
Collection collection = new ArrayList();
Student s1 = new Student("张三", 18);
Student s2 = new Student("李四", 18);
Student s3 = new Student("王五", 18);
Student s4 = new Student("赵六", 18);
Student s5 = new Student("钱七", 18);
//(1)添加数据
System.out.println("--------------添加元素-----------");
collection.add(s1);
collection.add(s2);
collection.add(s3);
collection.add(s4);
collection.add(s5);
System.out.println("元素个数" + collection.size());
System.out.println(collection.toString());
//(2)删除
System.out.println("--------------删除元素-----------");
collection.remove(s1);
System.out.println("删除后元素个数" + collection.size());
System.out.println(collection.toString());
//(3)清空 注意:删除或清空集合后集合对象并不会消失,因为仅仅删除对象在集合中的地址,真实的对象还在堆中;
// collection.clear();
// System.out.println("清空集合后元素个数" + collection.size());
//(4)遍历-增强for循环方式
System.out.println("--------使用增强for循环遍历---------");
for (Object object : collection) {
Student s = (Student) object;
System.out.println(s);
}
//(5)遍历-iterator(迭代器)方式:hasNext(); next(); remove()
//迭代过程中不能使用Collection的删除方式
System.out.println("---------使用迭代器方式遍历---------");
Iterator iterator = collection.iterator();
while (iterator.hasNext()){
Student s = (Student) iterator.next();
System.out.println(s);
}
//(6)判断
System.out.println("---------判断集合中元素---------");
System.out.println(collection.contains(s2));
}
}