1. 什么是数据结构:将数据按照一定结构组合起来,不同的组合方式会有不同的效率,不同的使用场景。分为线性结构:数组、链表、队列、栈等,和非线性结构:树、图、表等及其衍生类结构。
2. 数组:int[] a; a = new int[10]; 如果只执行int[] a;只是在栈上创建一个引用变量,并未赋值。只有当a = new int[10]才会在堆上真正的分配空间。(栈和堆的区别?)
思考:数组和ArrayList的区别
a. 最大的区别就是数组高效但是容量固定无法动态改变、ArrayList容量可动态改变但牺牲效率;
b. ArrayList当长度不够的时候会自动生成一个是原来2倍的数组,然后将内容全部迁移至新的数组(扩容);
c. list删除元素其实就是构建另一个,少一个元素的数组来代替这个老数组;(No,不是这样的,居然还涉及到JNI,调用arraycopy(Object src, int srcPos, Object dest, int destPos, int length)),增加和删除同理;
查看了java ArrayList删除元素的原码:
/**
* Removes the element at the specified position in this list.
* Shifts any subsequent elements to the left (subtracts one from their
* indices).
*
* @param index the index of the element to be removed
* @return the element that was removed from the list
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public E remove(int index) {
rangeCheck(index);
modCount++;
E oldValue = elementData(index);
int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[--size] = null; // Let gc do its work
return oldValue;
}