Java集合类库list(1)ArrayList实例

复制代码
public class ArrayListTest {

    public static void main(String[] args) {
        //创建空的ArrayList列表
        ArrayList al = new ArrayList();
        //添加元素
        al.add("hello");//在列表末尾添加元素
        al.add(null);//ArrayList允许null
        al.add(new Boolean(true));//基本数据类型如int,double,boolean自动加包成相应的对象
        al.add(new Integer(123));//基本数据类型如int,double,boolean自动加包成相应的对象
        al.add(new Double(100.12));//基本数据类型如int,double,boolean自动加包成相应的对象
        al.add(3, null);
        System.out.println(al);
        
        //删除元素
        al.remove(3);//删除指定索引的元素
        //al.remove(5);索引越界
        al.add(null);
        System.out.println(al);
        al.remove("hello");
        al.remove(null);//列表中有多个相同的元素,只会删除第一个
        System.out.println(al);
        //al.remove(456);//456会识别为索引,索引越界
        System.out.println(al.remove(new Integer(345)));//remove返回的是一个Boolean类型的,如果列表中有该元素,则返回true,然后在删除该元素;如果没有该元素,则返回false,列表不受影响
        System.out.println(al);
        //修改数据
        al.set(1, false);
        System.out.println(al);
        //查询元素
        Object o = al.get(2);//get返回的是object的类型
        System.out.println(o);
        
        //遍历ArrayList3种方式
        System.out.println("--for循环--");
        for(int i = 0; i <al.size(); i++){
            Object o1 = al.get(i);
            System.out.println(o1);
        }
        System.out.println("--foreach--");
        for(Object o1:al){
            System.out.println(o1);
        }
        System.out.println("--iterator--");
        Iterator it = al.iterator();
        while(it.hasNext()){
            Object o1 = it.next();
            System.out.println(o1);
        }
        System.out.println(al.isEmpty());//列表是否为空?
        System.out.println(al.size());//返回列表的长度
    }

}
复制代码

 

posted @   高冷就是范儿  阅读(654)  评论(0编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示