集合的增、删、遍历


增,删,遍历

  • 增加 .add()
  • 删除 .remove()
  • 遍历 for或者iterator
  • 判断 .contains
    .isEmpty

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

public class Demo01 {
    public static void main(String[] args) {
        //创建集合
        Collection tree = new ArrayList();
        //1.添加集合元素
        tree.add("苹果");
        tree.add("榴莲");
        tree.add("香蕉");
        System.out.println(tree);
        System.out.println("总数:"+tree.size());

        //2.移除集合元素
        /*  tree.remove("苹果");
        System.out.println("总数:"+tree.size());
        tree.clear();
        System.out.println("总数:"+tree.size());
        */

        //3.遍历集合
        System.out.println("--------------增强for循环------------------");
        for (Object o : tree) {
            System.out.println(o);
        }
        System.out.println("--------------iterator迭代器循环------------------");
        Iterator A =tree.iterator();
        while(A.hasNext()){
            String next = (String) A.next();
            System.out.println(next);
            //tree.remove  不允许使用原对象删除
            A.remove();
        }
        //4.判断
        System.out.println(tree.contains("苹果"));
        System.out.println(tree.isEmpty());
    }
}