List实现类
ArrayList:
### 源码分析:
DEFAULT_CAPACITY=10;默认容量(注意:如果没有向集合中添加任何元素,容量为0,添加一个元素之后,容量为10),每次扩容大小是原来的1.5倍。
elementData:存放元素的数组
size:实际大小
add():添加元素,代码如下:
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
private void ensureCapacityInternal(int minCapacity) {
ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
}
private static int calculateCapacity(Object[] elementData, int minCapacity) {
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {//elementData 和 DEFAULTCAPACITY_EMPTY_ELEMENTDATA初始都为0
return Math.max(DEFAULT_CAPACITY, minCapacity);//DEFAULT_CAPACITY初始为10
}
return minCapacity;//minCapacity为10
}
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
// overflow-conscious code
if (minCapacity - elementData.length > 0)//10-0大于0,执行grow();
grow(minCapacity);
}
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;//0
int newCapacity = oldCapacity + (oldCapacity >> 1);//0
if (newCapacity - minCapacity < 0)//-10
newCapacity = minCapacity;
if (newCapacity - MAX_ARRAY_SIZE > 0)// MAX_ARRAY_SIZE特别大,所以为负数,不成立
newCapacity = hugeCapacity(minCapacity);
// minCapacity is usually close to size, so this is a win:
elementData = Arrays.copyOf(elementData, newCapacity);//将10赋给elementData
}
vector:
vector使用较少,一般是作为面试题,只做了解就好。
方法与ArrayList类似,只不过它有一个特有遍历方法(使用枚举器),代码如下:
import java.util.Enumeration;
import java.util.Vector;
public class Demo1 {
public static void main(String[] args) {
//使用枚举器进行遍历
Vector vector = new Vector<>();
//随意添加两个数据
vector.add("菜名");
vector.add("小女");
Enumeration elements = vector.elements();
while (elements.hasMoreElements()){
String o = (String) elements.nextElement();
System.out.println(o);
}
}
}
LinkedList:
import java.util.LinkedList;
public class Demo {
public static void main(String[] args) {
LinkedList linkedList = new LinkedList();
Student s1 = new Student("小明",11,1);
Student s2 = new Student("小红",12,2);
Student s3 = new Student("小李",13,3);
linkedList.add(s1);
linkedList.add(s2);
linkedList.add(s3);
System.out.println("删除之前:"+linkedList.size());
System.out.println(linkedList.toString());
linkedList.remove(0);
System.out.println("删除之后:"+linkedList.size());
//3.遍历
//3.1 普通for循环,与ArrayList()基本相同,代码略
//3.2 增强for循环,与ArrayList()基本相同,代码略
//3.3 使用迭代器,与ArrayList()基本相同,代码略
//3.4 使用列表迭代器,与ArrayList()基本相同,代码略
//4.判断,与ArrayList()基本相同,代码略
//5.获取
System.out.println(linkedList.indexOf(s2));
}
}
ArrayList与LinkedList的区别:
ArrayList:必须开辟连续空间,查询快,增删慢;
LinkedList:无需开辟连续空间,查询慢,增删快;
标签:vector,LinkedList,ArrayList,elementData,List,minCapacity,linkedList From: https://www.cnblogs.com/mokuiran/p/16585118.html