集合
学集合
- 数据如何[增,删,改,查]
- 每种集合类的特点
集合的区别
ArrayList 底层是数组
查询较快
LinkedList底层是链表
添加,删除比较快
ArrayList
集合和数组的区别:
- 共同点: 都是存储数据的容器
- 不同点:数组的容量是固定的,集合的容量是可变的
ArrayList的构造方法和添加方法
方法 | 说明 |
---|---|
public ArrayList() | 创建一个空的集合对象 |
public boolean add(E e) | 将指定的元素追加到此集合的末尾 |
public void add(int index, E element) | 自此集合中的指定位置插入指定的元素 |
Arraylist< E>:
可调整大小的数组实现
< E >:是一种特殊的数据类型,泛型.
ArrayList类的常用方法
方法 | 说明 |
---|---|
public boolean remove(Object o) | 删除指定的元素,返回删除是否成功 |
public E remove(int index) | 删除指定索引处的元素,返回被删除的元素 |
public E set(int index , E element) | 修饰指定索引处的元素,返回被修改的元素 |
public E get(int index) | 返回指定索引处的元素 |
public int size() | 返回集合中的元素的个数 |
public class ArrayListDemo02 {
public static void main(String[] args) {
//创建集合
ArrayList<String> array = new ArrayList<String>();
//添加元素
array.add("hello");
array.add("world");
array.add("java");
//public boolean remove(Object o):删除指定的元素,返回删除是否成功
// System.out.println(array.remove("world"));
// System.out.println(array.remove("javaee"));
//public E remove(int index):删除指定索引处的元素,返回被删除的元素
// System.out.println(array.remove(1));
//IndexOutOfBoundsException
// System.out.println(array.remove(3));
//public E set(int index,E element):修改指定索引处的元素,返回被修改的元素
// System.out.println(array.set(1,"javaee"));
//IndexOutOfBoundsException
// System.out.println(array.set(3,"javaee"));
//public E get(int index):返回指定索引处的元素
// System.out.println(array.get(0));
// System.out.println(array.get(1));
// System.out.println(array.get(2));
//System.out.println(array.get(3)); //?????? 自己测试
//public int size():返回集合中的元素的个数
System.out.println(array.size());
//输出集合
System.out.println("array:" + array);
}
}
遍历集合
-
基本for循环,需要引入下标
-
增强版的for循环 for(元素: 集合)
-
lambada表达式