Collection 体系集合
Collection 父接口
-
特点:代表一组任意类型的对象,无序、无下标、不能重复
-
方法:
-
public class Demo01 { /*Collection接口的使用 1.建立元素 2.删除元素 3.遍历元素 4.判断 */ public static void main(String[] args) { // 创建集合 Collection collection = new ArrayList(); // 1.建立元素 collection.add("苹果"); collection.add("榴莲"); collection.add("西瓜"); System.out.println("元素数量"+collection.size()); System.out.println(collection); // 2.删除元 // collection.remove("西瓜"); // collection.clear(); // System.out.println("元素数量"+collection.size()); // 3.遍历元素 重点! // (1)增强for for(Object object : collection){ System.out.println(object); } // (2)使用迭代器(专门用来遍历集合的一种方式) // hasNext(); 有没有下一个元素 // next(); 获取下一个元素 // remove(); 删除当前元素 System.out.println("---------------------------------------------"); Iterator it = collection.iterator(); while (it.hasNext()){ String object = (String)it.next(); System.out.println(object); // 使用过程中 不能使用 collection 删除方法 // collection.remove(object); // it.remove(); } System.out.println("元素数量"+collection.size()); // 4.判断 System.out.println(collection.contains("西瓜")); System.out.println(collection.isEmpty()); } }
Collection 使用 保存学生类对象
-
public class Demo02 { /* Collection的使用 保存学生类 */ public static void main(String[] args) { // 新建Collection对象 Collection collection = new ArrayList(); Student s1 = new Student("张三",20); Student s2 = new Student("张四",21); Student s3 = new Student("张五",22); // 添加数据 collection.add(s1); collection.add(s2); collection.add(s3); System.out.println("元素个数:"+collection.size()); System.out.println(collection.toString()); // 删除 // collection.remove(s1); // collection.clear(); // System.out.println("元素个数:"+collection.size()); // 遍历 // (1)增强for for (Object object : collection) { Student s = (Student)object; System.out.println(s.toString()); } // (2)使用迭代器 // hasNext(); 有没有下一个元素 // next(); 获取下一个元素 // remove(); 删除当前元素 // 迭代过程中不能使用Collection删除方法 Iterator it = collection.iterator(); while (it.hasNext()){ Student s =(Student) it.next(); System.out.println(s.toString()); } // 判断 System.out.println(collection.contains(s1)); System.out.println(collection.isEmpty()); } }