Arraylist FIFO不是吗?

时间:2018-06-26 01:11:56

标签: java arraylist

我经历了arraylist docs。但是我在文档或Google中找不到关于被称为FIFO数据结构的信息吗?

直到,除非我不从列表中删除/删除元素,否则我将按照插入顺序相同的顺序获取元素。所以不能arraylist

3 个答案:

答案 0 :(得分:7)

ArrayList是随机访问。您可以在列表中的任何位置插入和删除元素。是的,您可以将其用作FIFO数据结构,但并不严格执行此行为。如果您需要严格的FIFO,请改用Queue

答案 1 :(得分:5)

否,它不是FIFO,而是由Array支持,并且它提供的方法使其像Array一样工作,您可以从其源代码中找到它们:

/**
 * 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 == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
 * will be expanded to DEFAULT_CAPACITY when the first element is added.
 */
// Android-note: Also accessed from java.util.Collections
transient Object[] elementData; // non-private to simplify nested class access

/**
 * Returns the element at the specified position in this list.
 *
 * @param  index index of the element to return
 * @return the element at the specified position in this list
 * @throws IndexOutOfBoundsException {@inheritDoc}
 */
public E get(int index);

/**
 * Replaces the element at the specified position in this list with
 * the specified element.
 *
 * @param index index of the element to replace
 * @param element element to be stored at the specified position
 * @return the element previously at the specified position
 * @throws IndexOutOfBoundsException {@inheritDoc}
 */
public E set(int index, E element);

/**
 * Appends the specified element to the end of this list.
 *
 * @param e element to be appended to this list
 * @return <tt>true</tt> (as specified by {@link Collection#add})
 */
public boolean add(E e);

因此,操作数据的方式是无限的,如果要使用FIFO,请考虑使用QueueFIFO功能由方法提供(使用{{1} })):

ArrayDeque

答案 2 :(得分:0)

否,对于FIFO,您可能希望使用LinkedListQueue实现之一。