ArrayList:善于随机访问,在中间执行插入、删除较慢
LinkedList:善于中间操作,憾于随机访问
分析ArrayList底层何时开辟数组空间
List list = new ArrayList<>();执行的操作
1,new ArrayList()此时并没有为底层数组开辟任何空间List list = new ArrayList<>();System.out.println(list.size());由源码分析可见,当类加载到虚拟机的时候,静态变量DEFAULTCAPACITY_EMPTY_ELEMENTDATA得到初始化public ArrayList() {this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;}private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {}; 为{}空数组//size()方法返回成员变量sizeprivate int size; //初始值为0public int size() {return size;}//isEmpty方法此时同size()方法一样public boolean isEmpty() {return size == 0;}2,执行add()操作public boolean add(E e) {//此时size为0ensureCapacityInternal(size + 1); // Increments modCount!!//为第0个元素赋值elementData[size++] = e;return true;}3,分析ensureCapacityInternal(size + 1)的操作ensureCapacityInternal(1)3-1,进入该方法private void ensureCapacityInternal(1) {ensureExplicitCapacity(calculateCapacity(elementData, 1));}3-2,进入calculateCapacity(elementData, 1)方法此时elementData已经通过构造器已经获得了DEFAULTCAPACITY_EMPTY_ELEMENTDATA的值 minCapacity为1private static int calculateCapacity(Object[] elementData, int minCapacity) {//判断该数组是否等于成员变量DEFAULTCAPACITY_EMPTY_ELEMENTDATA定义的初始值//其实构建new ArrayList()的时候 已经将DEFAULTCAPACITY_EMPTY_ELEMENTDATA赋值给了elementDataif (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {//获取俩参数的最大值 即DEFAULT_CAPACITY=10return Math.max(DEFAULT_CAPACITY, minCapacity);}return minCapacity;}3-3,回到ensureExplicitCapacity(10)private void ensureExplicitCapacity(int minCapacity) {modCount++;//代表了当前集合执行的修改记录数// overflow-conscious codeif (minCapacity - elementData.length > 0)grow(minCapacity);}3-4,进入grow方法 grow(10)private void grow(int minCapacity) {// overflow-conscious codeint oldCapacity = elementData.length;//elementData.length =0int newCapacity = oldCapacity + (oldCapacity >> 1);//newCapacity = 0if (newCapacity - minCapacity < 0)newCapacity = minCapacity;//将10赋值给newCapacityif (newCapacity - MAX_ARRAY_SIZE > 0)newCapacity = hugeCapacity(minCapacity);// minCapacity is usually close to size, so this is a win:elementData = Arrays.copyOf(elementData, newCapacity);//为空数组开辟10个空间}验证:Object[] temp ={}; 为其开辟空间Object[] temp ={};System.out.println(temp.length);System.out.println(temp==null);//即使是{} 也不能称为nulltemp = Arrays.copyOf(temp,10);System.out.println(temp.length);System.out.println(temp==null);
何时对Array List扩容
/*** ArrayList<Object> objects = new ArrayList<>(); 不开辟任何空间* 当执行第一次add的时候 默认开辟10个空间* 第一次扩容发生在第11次添加元素的时候* 扩充容量为 object.size()+(object.size >> 1) 就是扩充1.5倍*/public class ListApp2 {public static void main(String[] args) {final ArrayList<Object> objects = new ArrayList<>();objects.add("a");objects.add("a");objects.add("a");objects.add("a");objects.add("a");objects.add("a");objects.add("a");objects.add("a");objects.add("a");objects.add("a");objects.add("bb");System.out.println(objects.size());}}//当最后一次添加 容量不足的时候private void grow(int minCapacity) {// overflow-conscious codeint oldCapacity = elementData.length;int newCapacity = oldCapacity + (oldCapacity >> 1); //扩容1.5倍if (newCapacity - minCapacity < 0)newCapacity = minCapacity;if (newCapacity - MAX_ARRAY_SIZE > 0)newCapacity = hugeCapacity(minCapacity);// minCapacity is usually close to size, so this is a win:elementData = Arrays.copyOf(elementData, newCapacity);}
list的contains和remove方法是如何对自定义对象执行的
原理同俩对象equals的比较
public class People {private String name;private int age;People(){}People(String name,int age){this.name = name;this.age = age;}@Overridepublic boolean equals(Object o) {System.out.println("equals 执行了");if (this == o) return true;if (o == null || getClass() != o.getClass()) return false;People people = (People) o;return age == people.age &&Objects.equals(name, people.name);}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}/*@Overridepublic String toString() {return "People{" +"name='" + name + '\'' +", age=" + age +'}';}*/}public class ListApp4 {public static void main(String[] args) {People p1 = new People("aa",12);People p2 = new People("bb",13);People p3 = new People("cc",14);List list = new ArrayList<>();list.add(p1);list.add(p2);list.add(p3);//System.out.println(list);People p4 = new People("aa",12);//站在用户的角度去考虑的话 p4和p1是同一个人//在没有重写equals的时候 == 与equals判断的都是引用地址值//System.out.println(p1 == p4);//System.out.println(p1.equals(p4));//此时重写equals 就是说判断了俩对象的内容//list.remove(p4);if(list.contains(p4)){System.out.println("集合中包含有和p4一样的对象");}System.out.println("p1的hashcode值:"+p1);System.out.println("p4的hashcode值:"+p4);}}//contains源码分析 最后执行的源码如下public int indexOf(Object o) {if (o == null) {for (int i = 0; i < size; i++)if (elementData[i]==null)return i;} else {for (int i = 0; i < size; i++)if (o.equals(elementData[i]))//底层是equlas进行判断的return i;}return -1;}//removepublic boolean remove(Object o) {if (o == null) {for (int index = 0; index < size; index++)if (elementData[index] == null) {fastRemove(index);return true;}} else {for (int index = 0; index < size; index++)if (o.equals(elementData[index])) {fastRemove(index);return true;}}return false;}
ArrayList使用特点
public class ListFeatures {public static void main(String[] args) {Random rand = new Random(47);List<Pet> pets = Pets.list(7);//获取所有的宠物集合System.out.println("1: " + pets);Hamster h = new Hamster();pets.add(h); // Automatically resizesSystem.out.println("2: " + pets);System.out.println("3: " + pets.contains(h));pets.remove(h); // Remove by objectPet p = pets.get(2);System.out.println("4: " + p + " " + pets.indexOf(p));Pet cymric = new Cymric();//重新的new了一个System.out.println("5: " + pets.indexOf(cymric));System.out.println("6: " + pets.remove(cymric));//移除一个没有的对象// Must be the exact object:System.out.println("7: " + pets.remove(p));System.out.println("8: " + pets);pets.add(3, new Mouse()); // Insert at an indexSystem.out.println("9: " + pets);List<Pet> sub = pets.subList(1, 4);System.out.println("subList: " + sub);System.out.println("10: " + pets.containsAll(sub));Collections.sort(sub); // In-place sortSystem.out.println("sorted subList: " + sub);// Order is not important in containsAll(): 排过序的list 是否可以使用containsAllSystem.out.println("11: " + pets.containsAll(sub));//顺序对于containsAll来说 不重要Collections.shuffle(sub, rand); // Mix it upSystem.out.println("shuffled subList: " + sub);System.out.println("11-shuffled "+pets);System.out.println("12: " + pets.containsAll(sub));//再次证明顺序对于containsAll来说 不重要List<Pet> copy = new ArrayList<>(pets);sub = Arrays.asList(pets.get(1), pets.get(4));// [9,Rat, Manx, Mutt, Mouse, Pug, Cymric, Pug]// shuffled subList: [Rat, Mouse, Manx, Mutt, Pug, Cymric, Pug]System.out.println("sub: " + sub);//[Mouse, Pug] 改变子集的顺序 也是改变了原有集合的顺序copy.retainAll(sub);//交集的操作System.out.println("13: " + copy);copy = new ArrayList<>(pets); // Get a fresh copy [Rat, Mouse, Manx, Mutt, Pug, Cymric, Pug]copy.remove(2); // Remove by indexSystem.out.println("14: " + copy);copy.removeAll(sub); // Only removes exact objects ;Mouse Pug不在一起System.out.println("15: " + copy);copy.set(1, new Mouse()); // Replace an elementSystem.out.println("16: " + copy);copy.addAll(2, sub); // Insert a list in the middleSystem.out.println("17: " + copy);System.out.println("18: " + pets.isEmpty());pets.clear(); // Remove all elementsSystem.out.println("19: " + pets);System.out.println("20: " + pets.isEmpty());//[] isEmpty为true 即恢复到new的状态pets.addAll(Pets.list(4));System.out.println("21: " + pets);Object[] o = pets.toArray();//集合可以转为数组System.out.println("22: " + o[3]);Pet[] pa = pets.toArray(new Pet[0]);System.out.println("23: " + pa[3].id());}}
