java.util.ArrayList

import java.util.List;
import java.util.ArrayList;

public class LiwlArrayList {
    public static void main(String[] args){
        /* void add(); void add(int index, E element);
        * E remove(int index);
        * boolean remove(Object o);
        * void clear();
        * E set(int index,E element);
        * E get(int index);
        * boolean contains(Object o);
        * int size();
        * Object[] toArray();
        */
        List<String> course = new ArrayList<>();
        course.add("语文");
        course.add("数学");
        System.out.println("课程表的大小:"+course.size());
        for(int i = 0; i < course.size(); i++){
            System.out.println("第" + (i+1) + "节课:" + course.get(i));
        }
        course.add(1,"英语");
        System.out.println("在第1节后增加[英语]以后:" + course);
        System.out.println("获取第3节课程:" + course.get(2));
        if (course.contains("语文")){
            System.out.println("课程包含语文,修改为体育吧");
            course.set(0,"体育");
            System.out.println("现在的课程表是:" + course);
        }

        String a = course.remove(1);
        System.out.println("被移除的课程:" + a);

        if(course.remove("英语")){
            System.out.println("移除了英语");
        }else{
            System.out.println("已经移除了英语,课程表没有英语");
        }

        System.out.println("移除第2节课程后后:" + course);

        /*将动态数组ArrayList对象转为String数组*/
        String[] arr = new String[course.size()];
        course.toArray(arr);
        for(String item: arr){
            System.out.println(item);
        }

        course.clear();
        System.out.println("清理全部课程后:" + course);
    }
}
posted @ 2022-09-15 15:43  liwldev  阅读(242)  评论(0编辑  收藏  举报