集合
作用(容器):对多个数据存储
数组在存储多个数据的特点:
集合框架:
- Collection接口:单列数据
- List 接口:有序可重复数据 “动态数组” ,主要实现类:Arrylist、linkedlist、vector
- Set接口:无序不可重复数据 主要实现类:Hashset Linkedhashset 、treeset
- Map接口:双列数据(key-value)主要实现类:hashmap linkedhashmap、hashtable properties
Collection 接口
**
**
//8.集合转数组:toArray()
Object[] arr = coll.toArray();
for(int i = 0;i < arr.length;i++){
System.out.println(arr[i]);
}
//数组转集合:调用Arrays类的静态方法asList()
// 通过包装类 才能将数组元素挨个传入集合中,否则作为一个整体
List arr2 = Arrays.asList(new int[]{123, 456});
System.out.println(arr2.size());//1
List arr3 = Arrays.asList(new Integer[]{123, 456});
System.out.println(arr3.size());//2
- 集合对象每次调用iterator()方法都得到一个全新的迭代器对象,默认游标都在集合的第一个元素之前。
- 内部定义了remove(),可以在遍历的时候,删除集合中的元素。此方法不同于集合直接调用remove()
//遍历集合
//System.out.println(iterator.next());打印一个元素 并往后移光标
while(iterator.hasNext()){
System.out.println(iterator.next()); //这里并不是iterator().hasNext()
}
Object obj = iterator.next(); //取出当前元素的值,并光标后移
增强型for循环:
当变量类型出写Object则可以遍历一切
//for 数组/集合类型 + 循环变量 :被循环集合/数组名称
int[] arr = new int[]{1,2,3,4,5,6,7,8,9};
for (int j: arr){
System.out.println(j);
int[] arr = new int[]{1,2,3,4,5,6,7,8,9};
for (Object j: arr){
System.out.println(j);
List接口
void add(intindex, Object ele):在index位置插入ele元素
boolean addAll(int index, Collection eles):从index位置开始将eles中的所有元素添加进来
Object get(int index):获取指定index位置的元素
int indexOf(Object obj):返回obj在集合中首次出现的位置
int lastIndexOf(Object obj):返回obj在当前集合中末次出现的位置
Object remove(int index):移除指定index位置的元素,并返回此元素
Object set(int index, Object ele):设置指定index位置的元素为ele
List subList(int fromIndex, int toIndex):返回从fromIndex到toIndex位置的子集合
请问ArrayList/LinkedList/Vector的异同?谈谈你的理解?ArrayList底层是什么?扩容机制?Vector和ArrayList的最大区别?