JAVA_ArrayList和HashSet
标签:from而在fontinflate依次UIarraypadnested
- ArrayList
ArrayList在Java中主要是以线性表的形式进行存储,其本质是数组,不过相对于数组的长度不可变这一缺点,其实行了长度可变策略,使你在使用时,感觉到其就是一个无限长度的数组,而在底层中,则是通过动态增加长度来实现的,ArrayList就像是排队,没来一个对象或者元素,都会被添加到末尾位置(默认情况下),当然也免不了熟人插队的情况,此时就要指定相应位置,位置之前的元素位置不变,位置之后的元素依次后遗一位。
ArrayLsit.class源码解析
由于源码函数较多,这里通过一个列子来解析一下背后的原理就行了。
public class ArrayListAndHashSet {
public static void main(String[] args) {
Person p1 = new Person(\”Jim\”, \”One\”);
Person p2 = new Person(\”Bob\”, \”two\”);
Person p3 = new Person(\”Jim\”, \”One\”);
// 测试List
List<Person> persons = new ArrayList<>();
persons.add(p1);
persons.add(p2);
persons.add(p3);
persons.add(p1);
System.out.println(\”persons.size() = \” + persons.size());
- List<Person> presons = new ArrayList<>();
这句执行了ArrayList的无参构造函数:
/**
* Constructs an empty list with an initial capacity of ten.
*/
public ArrayList() {
this.elementData =http://www.mamicode.com/ DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
通过无参构造函数,我们可以发现将elementData赋值为了DEFAULTCAPACITY_EMPTY_ELEMENTDATA,这个常量在源码中代表的含义是:
/**
* Shared empty array instance used for default sized empty instances. We
* distinguish this from EMPTY_ELEMENTDATA to know how much to inflate when
* first element is added.
*/
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = http://www.mamicode.com/{};
通过注释我们可以发现其是一个空的实例对象,为了和EMPTY_ELEMENTDATA进行区分用的,
然后是我们的elementData,通过注释可发现,当第一个元素被加进来的时候,数组的缓存长度将会变成DEFAULT_CAPACITY
/**
* The array buffer into which the elements of the ArrayList are stored.
* The capacity of the ArrayList is the length of this array buffer. Any
* empty ArrayList with elementData =http://www.mamicode.com/= DEFAULTCAPACITY_EMPTY_ELEMENTDATA
* will be expanded to DEFAULT_CAPACITY when the first element is added.
*/
transient Object[] elementData; // non-private to simplify nested class access
DEFAULT_CAPACITY的默认值是10
/**
* Default initial capacity.
*/
private static final int