一.List<E> 两大特点,有序,可重复 有序:集合中的元素有索引值,可以精确找到,按索引顺序排列 可重复:可以插入相同的值。 因为他继承了Collection 所以,也可以用迭代器去遍历集合,但是因为,他有索引,所以可以通过循环来遍历。 List<e> 创建集合的方法 如:代码中的A1 重要的方法: void add (int index,E ); 在些集合中指定的位置插入指定的元素,后面的元素依次向后移动 如代码中:A2 E remove(int index );删除指定索引处的元素,并返回被删除的对象 如代码中:A3 E set(int index ,E x );修改指定索引处的元素,并返回被修改的对象。如代码中:A4 E get(int index);返回指定索引处的元素 如代码中:A5 二.并发异常,在利用Iterator<E> 去遍历集合时,在中途使用add()时,会发生并发修改异常, 原因:使用Iterator<E> 下的next(),方法时,会运行checkForComodification()去检查,这个方法会检查集合的修改次数, add()方法没有回写标志的话,就会认为数据同时在修改,报ConcurrentModificationException 异常 eg: modCount:实际修改次数和expectModCount:q预期修改的值,迭代器调用next(),会做: if(modCount!=expectModCount ) 判断,如代码中的:A1 三. ListIterator 列表迭代器,可以解决上的并发修改异常问题,但是要调用该迭代器的add()方法,因为这个方法进行了回写集合修改值。如代码中的:A2 四.增加for循环,他的产生就是为了减少数组和集合的遍历,他的底层就是封装了Iterator()迭代器 格式: for(类名 变量 :集合名){ 变量 } 变是就是取出集中的元素 如代码中的:A3 五.集合遍历三种方式: 1.利用迭代器和while(hasnext(),next())进行遍历 如代码中的:A5 2.利用变通for循环和get(index),size();来进行遍历 如代码中的:A4 3.利用增强for循环 如代码中的:A3 六.数据结构 栈数据特点:先进后出 (水桶) 队列数据特点:先进先出 (管道) 数组结构:查询效率高,增删数据慢 因为:查询可以通行索引直接找到,而增加删除一个数据,需要把后面的数据都要移动下。 链式数据结构:增删数据快,查询效率底。因为:链式数据通常有一个链表值,存储的是指向下一个值,当增加,删除一个数据时,只需修改链表值就可以了, 不用移动后面的数据,但是,查询起来时,需要从头一个一个的对元素进行对比才能找到, 七.List类,下面有两个实现的类 ArrayList LinkedList ArrayList:数组结构的类 查询快,增删慢 LinkedList:链表结构的类 查询慢,增删快
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
public class ListDemoBy {
public static void main(String[] args) {
//定义一个集合,用于存储学生对象
List<Student> listTemp = new ArrayList<Student>();
//实例三个学生对象
Student studA = new Student("哈哈",34);
Student studB = new Student("呵呵", 28);
Student studC = new Student("嘿嘿", 18);
//向集合中添加对象
listTemp.add(studA);
listTemp.add(studB);
listTemp.add(studC);
//遍历集合
System.out.println("---Iterator遍历集合---A5--");
// 利用List<E>接口方法中的,
Iterator<Student> it = listTemp.iterator();
//while遍历循环
while (it.hasNext()){
Student itor = it.next(); //-->A1
/* -->iterator().next()方法中和add()中记录集合修改次数有冲突,add()没有回写记录值。
modCount:实际修改次数
expectModCount:q预期修改的值,
if(modCount!=expectModCount )
if(itor.getName().equals("嘿嘿")){
listTemp.add(new Student("哈哈",34));
}
*/
itor.Show();
}
System.out.println("---利用for循环遍历集合-- A4---");
for(int i=0;i<listTemp.size();i++){
Student stuT = listTemp.get(i);
stuT.Show();
}
System.out.println("---增加for循环遍历集合--A3---");
for(Student s : listTemp){
s.Show();
}
System.out.println("-------Listterator 遍历集合------");
ListIterator<Student> studList = listTemp.listIterator();
while (studList.hasNext()){
Student ss = studList.next();
if(ss.getName().equals("哈哈")){
studList.add(new Student("呵呵",34)); //-->A2
}
}
for(Student ss:listTemp){
ss.Show();
}
}
}