集合
集合与数组的区别为:
1.数组的长度固定,集合的不固定
2.数组可以存储基本类型和引用类型,集合中存储的元素类型只能是引用类型。
主要分为两个框架,分别为collection集合和map集合框架
Collection接口
1.collection中常用的难记方法:
-
1.1 contains(Object o):如果此 collection 包含指定的元素,则返回true。
-
1.2 containsAll(Collection<?> c):如果此 collection 包含指定 collection 中的所有元素,则返回 true。
-
1.3 isEmpty():如果此 collection 不包含元素,则返回true。
-
1.4 remove(Object o):从此 collection 中移除指定元素的单个实例,如果存在的话(可选操作)。
-
1.5 toArray():返回包含此 collection 中所有元素的数组。
编辑区域与预览区域中间;
代码:
Collection collection=new ArrayList();
//1添加
collection.add(111);//111自动装箱 new Integer(111)
collection.add(222);
collection.add("111");
collection.add("222");
//2删除
System.out.println("元素的个数:"+collection.size());
System.out.println("删除之前:"+collection);
collection.remove("111");
System.out.println("删除之后:"+collection.size());
System.out.println("删除之后:"+collection);
//3遍历
//3.1增强for循环
System.out.println("增强for.....");
for (Object object : collection) {
System.out.println(object);
}
//3.2使用迭代器
System.out.println("迭代器.....");
Iterator it=collection.iterator();
while(it.hasNext()){
Object obj=it.next();
System.out.println(obj);
}
2.List接口:
常用方法:
- indexOf(Object o):返回此列表中第一次出现的指定元素的索引;如果此列表不包含该元素,则返回 -1。
- set(int index, E element)用指定元素替换列表中指定位置的元素(可选操作)。
- 其他方法基本同collection
List接口的存储特点:
1. 相对有序存储,可以存储相同元素(不排重),可以通过下标访问集合元素
2.List接口中可以使用独有的迭代器ListIterator,具有反向遍历的功能
List接口的实现类:
ArrayList类:
特点:
1.实现了所有List接口的方法,并允许null存在,相对有序存储。
2.可以存储相同元素(不排重),可以通过下标访问集合元素,通过数组实现的集合。
3.存储结构:数组
代码: