由于最近在找工作,需要准备面试,所以需要去理解下基础知识,还是由于自己以前没有多注意基础知识的细节,现在来补下,发现LinkedList,ArrayList HashMp TreeMap数据结构很容易在编程也容易用到,但是基本在用的时候,就想的用法很简单,但是说到原理,其实很多人没有注意到的关于这四个数据结构,很多人都写了很多博客,我下面写的是我理解到。
一:ArrayList
ArrayList是List接口的可变数组的实现。实现了所有可选列表操作,并允许包括 null 在内的所有元素。除了实现 List 接口外,此类还提供一些方法来操作内部用来存储列表的数组的大小。该数据结构在多线程反问时候是不安全的,底层采用数据实现,下面看下源码:
public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
private static final long serialVersionUID = 8683452581122892189L;
/**
* Default initial capacity.
*/
private static final int DEFAULT_CAPACITY = 10;
如上,看见ArrayList实现List,然后默认大小为10.看下面实现的三种构造函数。
/**
* Constructs an empty list with the specified initial capacity.
*
* @param initialCapacity the initial capacity of the list
* @throws IllegalArgumentException if the specified initial capacity
* is negative
*/
public ArrayList(int initialCapacity) {
super();
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
this.elementData = new Object[initialCapacity];
}
/**
* Constructs an empty list with an initial capacity of ten.
*/
public ArrayList() {
super();
this.elementData = EMPTY_ELEMENTDATA;
}
/**
* Constructs a list containing the elements of the specified
* collection, in the order they are returned by the collection's
* iterator.
*
* @param c the collection whose elements are to be placed into this list
* @throws NullPointerException if the specified collection is null
*/
public ArrayList(Collection<? extends E> c) {
elementData = c.toArray();
size = elementData.length;
// c.toArray might (incorrectly) not return Object[] (see 6260652)
if (elementData.getClass() != Object[].class)
elementData = Arrays.copyOf(elementData, size, Object[].class);
}
然后可以通过读取ArrayList源码,发现整个过程都是操作的数组。
在获取数据的效率上比linkedList快的多