Java中ArrayList的使用

ArrayList是一个容量能够动态增长的动态数组。基本的ArrayList,善于随机访问元素,但插入和删除元素较慢。且ArrayList不是线程安全的,一般在单线程中使用,多线程一般用Vector或CopyOnWriteArrayList

添加、删除、修改、查找元素:

添加:.add(e)在list最后添加元素;.add(index, e)在索引位置添加元素e

删除:.remove(int index)按索引删;.remove(Object o)按元素内容删

修改:.set(index, e)将e放在index位置上,替换原来元素

查找:.indexOf(e)查找e出现的第一个位置并返回下标; lastIndexOf(e)查找e出现的最后一个位置并返回下标


获取、清空、获取list大小、是否包含,是否为空元素:

获取:.get(index)获取index位置处的元素并返回

清空:.clear()删除全部元素

获取list大小:.size()返回list中元素个数

是否包含:.contains(Object o)若list中含有元素返回true,否则返回false;

是否为空:.isEmpty()若list为空返回true,否则返回false


生成新的list(截取集合)、list比较:

生成新的list:.subList(fromIndex, toIndex)从原list中截取fromIndex(包含)到toIndex(不包含)形成新的list

list比较:list1.equals(list2)两个相等对象的equals方法一定为true,但两个hashcode相等的对象不一定是相等的对象


返回Iterator集合对象、转换为字符串、转为数组、集合类型转换:

返回Iterator集合对象: .iterator()

转换为字符串:.toString()

转为数组:.toArray();可能抛出java.lang.ClassCastException异常。是由于toArray()返回值是O把Object[]数组,将Object[]转换为其他类型会抛出异常,这是因为Java不支持向下转型

Integer[] integer = arrayList.toArray(new Integer[0]);

集合类型转换:

List<Object> listsStrings=new ArrayList<>();
  for (int i = 0; i < person.size(); i++) {
    listsStrings.add(person.get(i));
}


ArrayList遍历方法:

迭代器遍历:

Iterator<Integer> it = arrayList.iterator();
while(it.hasNext()){
    System.out.print(it.next() + " ");
}
索引值遍历:
for(int i = 0; i < arrayList.size(); i++){
   System.out.print(arrayList.get(i) + " ");
}
for循环遍历:

for(Integer number : arrayList){
   System.out.print(number + " ");
}

索引值遍历效率最高,for循环次之,迭代器遍历最低



猜你喜欢

转载自blog.csdn.net/lyp_1020k/article/details/79766331
今日推荐