11JAVA基础-集合

一、集合

`在这里插入图片描述

二、Collection类

Collection 是单列的顶层类。
Collection是接口。
创建对象需要借助多态。
//e为集合中数据类型
//ArrayList是List的实现类
Collection<e> collection= new ArrayList<e>();

1、 Collection的常用方法

Collection<String> collection= new ArrayList<String>();
//向collection中增加元素
boolean ad = collecion.add(String value);
//从collection中删除指定元素
boolean rem = collection.remove(String value);
//清除所有元素
void cle = collection.clear();
//判断是否为空
boolean isE = collection.isEmpty();
//集合中元素个数
int count = collection.size();

2、迭代器

Collection<String> collection= new ArrayList<String>();
//it 为迭代器对象
Iterator it = collection.Iterator();
迭代器对象方法
boolean result =  it.hasNext();//是否有下一个
String result = it.next();//下一个元素

三、List

有序的集合,有索引
List<String> list = new ArrayLsit<String>();
特有方法
//获取指定位置的元素
String s = list.get(int index);
//在指定位置加元素
String s = list.add(int index,String str);
//修改指定位置的元素
String s = list.set(int index,String str);
//删除指定位置的元素
String s = list.remove(int index);

迭代器

List的迭代器可以获取倒序遍历,
倒序遍历前提:指针位于集合最后一个元素
ListIterator<E> lis = list.listIterator();
boolean  lis.hasPrevious();
E lis.previous();

四、List的遍历方式

ArrayList<String> list = new ArrayList<E>();

1、使用迭代器

Iterator it = list.Iterator();
while(it.hasNext()){
	String value = it.next();
}

2、普通for

for(int i =0;i<list.size();i++){
		String s = list get(i);
}

3、增强for

for(String value : list){
		String s = value
}

五、ConcurrentModificationException异常

产生原因:
	迭代器是依靠集合生成的。
	如果在使用迭代器的时候同时通过集合来修改集合元素个数,那么迭代器无法正确识别集合元素个数,导致报错。
解决方案:
		1、通过迭代器修改个数
		2、获取元素的不采用迭代器,直接使用for循环
两种方案的差异:
		1、第一种加入的元直接加在当前迭代器指针位置的后一个
		2、第二种加载元素的最后一个

六、基本数据结构

1、栈

先进后出
进栈:压栈
出栈:弹栈

2、队列

先进先出

3、数组

查询方便
增加数据的时候,每次都需要新建一个新的数组,然后将旧数组的数据增加或者删除到新的数组。 比较耗时间。

4、链表

增删方便,
每一个元素保存元素数值、当前元素位置,下一个元素的位置
查询数据的时候每次都需要从头开始查询,比较耗时间。

猜你喜欢

转载自www.cnblogs.com/hatcher-h/p/12888488.html