ArrayList:善于随机访问,在中间执行插入、删除较慢
LinkedList:善于中间操作,憾于随机访问

分析ArrayList底层何时开辟数组空间

List list = new ArrayList<>();执行的操作

  1. 1,new ArrayList()此时并没有为底层数组开辟任何空间
  2. List list = new ArrayList<>();
  3. System.out.println(list.size());
  4. 由源码分析可见,当类加载到虚拟机的时候,静态变量DEFAULTCAPACITY_EMPTY_ELEMENTDATA得到初始化
  5. public ArrayList() {
  6. this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
  7. }
  8. private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {}; 为{}空数组
  9. //size()方法返回成员变量size
  10. private int size; //初始值为0
  11. public int size() {
  12. return size;
  13. }
  14. //isEmpty方法此时同size()方法一样
  15. public boolean isEmpty() {
  16. return size == 0;
  17. }
  18. 2,执行add()操作
  19. public boolean add(E e) {
  20. //此时size为0
  21. ensureCapacityInternal(size + 1); // Increments modCount!!
  22. //为第0个元素赋值
  23. elementData[size++] = e;
  24. return true;
  25. }
  26. 3,分析ensureCapacityInternal(size + 1)的操作
  27. ensureCapacityInternal(1)
  28. 3-1,进入该方法
  29. private void ensureCapacityInternal(1) {
  30. ensureExplicitCapacity(calculateCapacity(elementData, 1));
  31. }
  32. 3-2,进入calculateCapacity(elementData, 1)方法
  33. 此时elementData已经通过构造器已经获得了DEFAULTCAPACITY_EMPTY_ELEMENTDATA的值 minCapacity为1
  34. private static int calculateCapacity(Object[] elementData, int minCapacity) {
  35. //判断该数组是否等于成员变量DEFAULTCAPACITY_EMPTY_ELEMENTDATA定义的初始值
  36. //其实构建new ArrayList()的时候 已经将DEFAULTCAPACITY_EMPTY_ELEMENTDATA赋值给了elementData
  37. if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
  38. //获取俩参数的最大值 即DEFAULT_CAPACITY=10
  39. return Math.max(DEFAULT_CAPACITY, minCapacity);
  40. }
  41. return minCapacity;
  42. }
  43. 3-3,回到ensureExplicitCapacity(10)
  44. private void ensureExplicitCapacity(int minCapacity) {
  45. modCount++;//代表了当前集合执行的修改记录数
  46. // overflow-conscious code
  47. if (minCapacity - elementData.length > 0)
  48. grow(minCapacity);
  49. }
  50. 3-4,进入grow方法 grow(10)
  51. private void grow(int minCapacity) {
  52. // overflow-conscious code
  53. int oldCapacity = elementData.length;//elementData.length =0
  54. int newCapacity = oldCapacity + (oldCapacity >> 1);//newCapacity = 0
  55. if (newCapacity - minCapacity < 0)
  56. newCapacity = minCapacity;//将10赋值给newCapacity
  57. if (newCapacity - MAX_ARRAY_SIZE > 0)
  58. newCapacity = hugeCapacity(minCapacity);
  59. // minCapacity is usually close to size, so this is a win:
  60. elementData = Arrays.copyOf(elementData, newCapacity);//为空数组开辟10个空间
  61. }
  62. 验证:Object[] temp ={}; 为其开辟空间
  63. Object[] temp ={};
  64. System.out.println(temp.length);
  65. System.out.println(temp==null);//即使是{} 也不能称为null
  66. temp = Arrays.copyOf(temp,10);
  67. System.out.println(temp.length);
  68. System.out.println(temp==null);

何时对Array List扩容

  1. /**
  2. * ArrayList<Object> objects = new ArrayList<>(); 不开辟任何空间
  3. * 当执行第一次add的时候 默认开辟10个空间
  4. * 第一次扩容发生在第11次添加元素的时候
  5. * 扩充容量为 object.size()+(object.size >> 1) 就是扩充1.5倍
  6. */
  7. public class ListApp2 {
  8. public static void main(String[] args) {
  9. final ArrayList<Object> objects = new ArrayList<>();
  10. objects.add("a");
  11. objects.add("a");
  12. objects.add("a");
  13. objects.add("a");
  14. objects.add("a");
  15. objects.add("a");
  16. objects.add("a");
  17. objects.add("a");
  18. objects.add("a");
  19. objects.add("a");
  20. objects.add("bb");
  21. System.out.println(objects.size());
  22. }
  23. }
  24. //当最后一次添加 容量不足的时候
  25. private void grow(int minCapacity) {
  26. // overflow-conscious code
  27. int oldCapacity = elementData.length;
  28. int newCapacity = oldCapacity + (oldCapacity >> 1); //扩容1.5倍
  29. if (newCapacity - minCapacity < 0)
  30. newCapacity = minCapacity;
  31. if (newCapacity - MAX_ARRAY_SIZE > 0)
  32. newCapacity = hugeCapacity(minCapacity);
  33. // minCapacity is usually close to size, so this is a win:
  34. elementData = Arrays.copyOf(elementData, newCapacity);
  35. }

list的contains和remove方法是如何对自定义对象执行的

原理同俩对象equals的比较

  1. public class People {
  2. private String name;
  3. private int age;
  4. People(){
  5. }
  6. People(String name,int age){
  7. this.name = name;
  8. this.age = age;
  9. }
  10. @Override
  11. public boolean equals(Object o) {
  12. System.out.println("equals 执行了");
  13. if (this == o) return true;
  14. if (o == null || getClass() != o.getClass()) return false;
  15. People people = (People) o;
  16. return age == people.age &&
  17. Objects.equals(name, people.name);
  18. }
  19. public String getName() {
  20. return name;
  21. }
  22. public void setName(String name) {
  23. this.name = name;
  24. }
  25. public int getAge() {
  26. return age;
  27. }
  28. public void setAge(int age) {
  29. this.age = age;
  30. }
  31. /*@Override
  32. public String toString() {
  33. return "People{" +
  34. "name='" + name + '\'' +
  35. ", age=" + age +
  36. '}';
  37. }*/
  38. }
  39. public class ListApp4 {
  40. public static void main(String[] args) {
  41. People p1 = new People("aa",12);
  42. People p2 = new People("bb",13);
  43. People p3 = new People("cc",14);
  44. List list = new ArrayList<>();
  45. list.add(p1);
  46. list.add(p2);
  47. list.add(p3);
  48. //System.out.println(list);
  49. People p4 = new People("aa",12);//站在用户的角度去考虑的话 p4和p1是同一个人
  50. //在没有重写equals的时候 == 与equals判断的都是引用地址值
  51. //System.out.println(p1 == p4);
  52. //System.out.println(p1.equals(p4));//此时重写equals 就是说判断了俩对象的内容
  53. //list.remove(p4);
  54. if(list.contains(p4)){
  55. System.out.println("集合中包含有和p4一样的对象");
  56. }
  57. System.out.println("p1的hashcode值:"+p1);
  58. System.out.println("p4的hashcode值:"+p4);
  59. }
  60. }
  61. //contains源码分析 最后执行的源码如下
  62. public int indexOf(Object o) {
  63. if (o == null) {
  64. for (int i = 0; i < size; i++)
  65. if (elementData[i]==null)
  66. return i;
  67. } else {
  68. for (int i = 0; i < size; i++)
  69. if (o.equals(elementData[i]))//底层是equlas进行判断的
  70. return i;
  71. }
  72. return -1;
  73. }
  74. //remove
  75. public boolean remove(Object o) {
  76. if (o == null) {
  77. for (int index = 0; index < size; index++)
  78. if (elementData[index] == null) {
  79. fastRemove(index);
  80. return true;
  81. }
  82. } else {
  83. for (int index = 0; index < size; index++)
  84. if (o.equals(elementData[index])) {
  85. fastRemove(index);
  86. return true;
  87. }
  88. }
  89. return false;
  90. }

ArrayList使用特点

  1. public class ListFeatures {
  2. public static void main(String[] args) {
  3. Random rand = new Random(47);
  4. List<Pet> pets = Pets.list(7);
  5. //获取所有的宠物集合
  6. System.out.println("1: " + pets);
  7. Hamster h = new Hamster();
  8. pets.add(h); // Automatically resizes
  9. System.out.println("2: " + pets);
  10. System.out.println("3: " + pets.contains(h));
  11. pets.remove(h); // Remove by object
  12. Pet p = pets.get(2);
  13. System.out.println("4: " + p + " " + pets.indexOf(p));
  14. Pet cymric = new Cymric();//重新的new了一个
  15. System.out.println("5: " + pets.indexOf(cymric));
  16. System.out.println("6: " + pets.remove(cymric));//移除一个没有的对象
  17. // Must be the exact object:
  18. System.out.println("7: " + pets.remove(p));
  19. System.out.println("8: " + pets);
  20. pets.add(3, new Mouse()); // Insert at an index
  21. System.out.println("9: " + pets);
  22. List<Pet> sub = pets.subList(1, 4);
  23. System.out.println("subList: " + sub);
  24. System.out.println("10: " + pets.containsAll(sub));
  25. Collections.sort(sub); // In-place sort
  26. System.out.println("sorted subList: " + sub);
  27. // Order is not important in containsAll(): 排过序的list 是否可以使用containsAll
  28. System.out.println("11: " + pets.containsAll(sub));//顺序对于containsAll来说 不重要
  29. Collections.shuffle(sub, rand); // Mix it up
  30. System.out.println("shuffled subList: " + sub);
  31. System.out.println("11-shuffled "+pets);
  32. System.out.println("12: " + pets.containsAll(sub));//再次证明顺序对于containsAll来说 不重要
  33. List<Pet> copy = new ArrayList<>(pets);
  34. sub = Arrays.asList(pets.get(1), pets.get(4));// [9,Rat, Manx, Mutt, Mouse, Pug, Cymric, Pug]
  35. // shuffled subList: [Rat, Mouse, Manx, Mutt, Pug, Cymric, Pug]
  36. System.out.println("sub: " + sub);//[Mouse, Pug] 改变子集的顺序 也是改变了原有集合的顺序
  37. copy.retainAll(sub);//交集的操作
  38. System.out.println("13: " + copy);
  39. copy = new ArrayList<>(pets); // Get a fresh copy [Rat, Mouse, Manx, Mutt, Pug, Cymric, Pug]
  40. copy.remove(2); // Remove by index
  41. System.out.println("14: " + copy);
  42. copy.removeAll(sub); // Only removes exact objects ;Mouse Pug不在一起
  43. System.out.println("15: " + copy);
  44. copy.set(1, new Mouse()); // Replace an element
  45. System.out.println("16: " + copy);
  46. copy.addAll(2, sub); // Insert a list in the middle
  47. System.out.println("17: " + copy);
  48. System.out.println("18: " + pets.isEmpty());
  49. pets.clear(); // Remove all elements
  50. System.out.println("19: " + pets);
  51. System.out.println("20: " + pets.isEmpty());//[] isEmpty为true 即恢复到new的状态
  52. pets.addAll(Pets.list(4));
  53. System.out.println("21: " + pets);
  54. Object[] o = pets.toArray();//集合可以转为数组
  55. System.out.println("22: " + o[3]);
  56. Pet[] pa = pets.toArray(new Pet[0]);
  57. System.out.println("23: " + pa[3].id());
  58. }
  59. }