11JAVA基础-集合

1、集合

`在这里插入图片描述java

2、Collection类

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

一、 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();

二、迭代器

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

3、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();

4、List的遍历方式

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

一、使用迭代器

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

二、普通for

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

三、加强for

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

5、ConcurrentModificationException异常

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

6、基本数据结构

一、栈

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

二、队列

先进先出

三、数组

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

四、链表

增删方便,
每个元素保存元素数值、当前元素位置,下一个元素的位置
查询数据的时候每次都须要从头开始查询,比较耗时间。
相关文章
相关标签/搜索