list


list

  • 增加 .add()
  • 删除 .remove()
  • 遍历 for或者iterator
    .next()
    .previous()
  • 判断 .contains()
    .isEmpty()
  • 获取下标 .indexOf()


import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;


public class Demo01 {
    public static void main(String[] args) {
        //创建集合
        List 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  不允许使用原对象删除
        }
        System.out.println("--------------ListIterator迭代器循环------------------");
        //和iterator迭代器的区别,ListIterator可以向前或向后操作
        ListIterator B = tree.listIterator();
        while (B.hasNext()) {
            System.out.println(B.nextIndex()+":"+ B.next());
        }
        while (B.hasPrevious()){
            System.out.println(B.previousIndex()+":"+ B.previous());
        }

        System.out.println("--------------判断------------------");
        //4.判断
        System.out.println(tree.contains("苹果"));
        System.out.println(tree.isEmpty());
        //获取位置
        System.out.println(tree.indexOf("苹果"));
  System.out.println("-------------取部分集合-------------------");
        //补充方法sublist;返回子集合,含头不含尾
        List subList =tree.subList(1,2);
        System.out.println(subList);
    }
}