JAVA学习之路之ArrayList

集合基础

1.1背景

编程的时候如果要存储多个数据,使用长度固定的数组存储格式,不一定能满足我们的需求。

1.2集合概述

集合类的特点:提供一种可变的存储类型,存储的数据容量可以发生改变
集合类有很多,目前只学习:ArrayList

ArrayList <E>:
1.可调整大小的数组实现
2.<E>:是一种特殊的数据类型,泛型

如何使用

在出现E的的地方我们使用引用数据类型替换即可
举例:ArrayList <String>,ArrayList <Student>

1.3ArrayList构造方法和添加方法

方法名说明
public ArrayList()创建一个空的集合对象
public boolean add(E e)将指定的元素追加到此集合的末尾
public void add(int index,E element)在此集合指定位置插入指定的元素

代码演示:

import java.util.ArrayList;

public class ArrayListDemo1 {
    public static void main(String[] args) {
        //public ArrayList() 创建一个空的集合对象
        ArrayList<String> arrayList = new ArrayList<>();
        System.out.println(arrayList);
        //public boolean add(E e) 将指定的元素追加到此集合的末尾
        arrayList.add("hello");
        arrayList.add("world");
        System.out.println(arrayList);
        //public void add(int index,E element) 在此集合指定位置插入指定的元素
        arrayList.add(1,"java");
        System.out.println(arrayList);
        //IndexOutOfBoundsException 集合索引越界
        //arrayList.add(4,"case");



    }
}
运行结果:
[]
[hello, world]
[hello, java, world]

1.4ArrayList集合常用方法

方法名说明
public boolean remove(Object o)删除指定的元素,返回删除是否成功
public E remove (int index)删除指定索引处的元素,返回被删除的元素
public E set (int index)修改指定索引处的元素,返回修改的元素
public E get (int index)返回指定索引处的元素
public int size ()返回集合中元素的个数

代码演示:

import java.util.ArrayList;

public class ArrayListDemo2 {
    public static void main(String[] args) {
        ArrayList<String> arrayList = new ArrayList<>();
        arrayList.add("hello");
        arrayList.add("world");
        arrayList.add("java");
        System.out.println(arrayList);
        //public boolean remove(Object o)  删除指定的元素,返回删除是否成功
        //arrayList.remove("java");
        System.out.println(arrayList.remove("java"));
        System.out.println(arrayList);
        //public E remove (int index)   删除指定索引处的元素,返回被删除的元素
        System.out.println(arrayList.remove(0));
        System.out.println(arrayList);
        //public E set (int index)   修改指定索引处的元素,返回修改的元素
        System.out.println(arrayList.set(0,"helloworld"));
        System.out.println(arrayList);
        //public E get (int index)   返回指定索引处的元素
        System.out.println(arrayList.get(0));
        System.out.println(arrayList);
        //public int size ()  返回集合中元素的个数
        System.out.println(arrayList.size());
        System.out.println(arrayList);

    }
}
输出结果:
[hello, world, java]
true
[hello, world]
hello
[world]
world
[helloworld]
helloworld
[helloworld]
1
[helloworld]

进程已结束,退出代码为 0



1.5集合的遍历

for (int i = 0;i<arrayList.size();i++){
            String s = arrayList.get(i);
            System.out.println(s);
        }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值