1.集合的概念 对象的容器,实现了对对象常用的操作,类似数组功能。
2.集合和数组的区别 (1)数组长度固定,集合长度不固定 (2)数组可以存储基本数据类型和引用数据类型,集合只能存储引用数据类型
3.List接口的特点:有序、有下标、元素可重复;Set接口的特点:无序、无下标、元素不可重复。
4.Collection的使用
Collection collection = new ArrayList(); //添加元素 collection.add("苹果"); collection.add("西瓜"); collection.add("榴莲"); System.out.println(collection); //遍历元素 使用增强for;不能使用普通发for循环,普通for需要下标 for (Object object:collection) { System.out.println(object); } //使用迭代器来遍历 Iterator it = collection.iterator(); while (it.hasNext()){ String s=(String)it.next(); System.out.println(s); } //判断 System.out.println(collection.contains("西瓜"));
5.s3的写法是s4的简写
Student s3 = new Student("王五",21); Student s4 = new Student(); s4.setAge(20); s4.setName("dd");
6.ListIterator
//使用列表迭代器,和Iterator的区别,ListIterator可以向前或向后遍历,添加、删除、修改元素 ListIterator lit=list.listIterator(); System.out.println("------列表迭代器从前往后--------"); while(lit.hasNext()){ System.out.println(lit.nextIndex()+":"+lit.next()); } System.out.println("-----------------------------"); //从后往前 while(lit.hasPrevious()){ System.out.println(lit.previousIndex()+":"+lit.previous()); } //获取位置 System.out.println(list.indexOf("华为")); //补充方法subList,返回子集合,包含1不包含2 //list.subList(1,2); System.out.println(list.subList(1,2).toString());
7.ArrayList数组:默认容量为10,当存储的数据超过容量时,扩容的新空间是原来的1.5倍; 注意:如果没有向集合中添加元素时,容量为0,当开始添加第一个元素时,容量为10。