ArrayList底层原理
首先ArrayList的底层是使用动态数组来进行元素的存储。
优点:查询快,修改相对较慢
创建ArrayList时,底层会先创建一个长度为10的数组,使用一个size记录存储个数和下一个存储位置,当size大小等于数组长度时,数组将进行扩容,底层使用Arrays.copyOf()方法,每次扩容1.5倍。
集合遍历修改
for 循环
普通for循环配合自减操作可以完成集合的遍历修改
public class Test {
public static void main(String[] args) {
List<String> collection = new ArrayList<>();
collection.add("sss");
collection.add("sss");
collection.add("sssss");
collection.add(3,"sww");
Object[] strings = collection.toArray();
// collection.sort(Comparator.comparing(new Function<String, Integer>() {
// @Override
// public Integer apply(String s) {
// return -s.length();
// }
// }).reversed());
for (int i = 0; i< collection.size();i++){
if (collection.get(i).equals("sss")){
collection.remove("sss");
i--;
}
}
System.out.println(collection);
}
}
增强for循环
会出现相关错误
public class Test {
public static void main(String[] args) {
List<String> collection = new ArrayList<>();
collection.add("sss");
collection.add("sss");
collection.add("sssss");
collection.add(3,"sww");
Object[] strings = collection.toArray();
// collection.sort(Comparator.comparing(new Function<String, Integer>() {
// @Override
// public Integer apply(String s) {
// return -s.length();
// }
// }).reversed());
for (String s:collection){
if (s.equals("sss")){
collection.remove("sss");
}
}
System.out.println(collection);
}
}
forEach
底层原理就是增强for循环,同样会出现问题
public class Test {
public static void main(String[] args) {
List<String> collection = new ArrayList<>();
collection.add("sss");
collection.add("sss");
collection.add("sssss");
collection.add(3,"sww");
Object[] strings = collection.toArray();
// collection.sort(Comparator.comparing(new Function<String, Integer>() {
// @Override
// public Integer apply(String s) {
// return -s.length();
// }
// }).reversed());
collection.forEach(new Consumer<String>() {
@Override
public void accept(String s) {
if ("sss".equals(s)){
collection.remove("sss");
}
}
});
System.out.println(collection);
}
}
Iterator迭代器
直接使用集合进行删除(报错)
使用Iterator的remove方法不会报错
public class Test {
public static void main(String[] args) {
List<String> collection = new ArrayList<>();
collection.add("sss");
collection.add("sss");
collection.add("sssss");
collection.add(3,"sww");
Object[] strings = collection.toArray();
// collection.sort(Comparator.comparing(new Function<String, Integer>() {
// @Override
// public Integer apply(String s) {
// return -s.length();
// }
// }).reversed());
Iterator<String> iterator = collection.iterator();
while (iterator.hasNext()){
if ("sss".equals(iterator.next())){
// collection.remove("sss"); 错误的方法,会引发错误
iterator.remove();
}
}
System.out.println(collection);
}
}