LinkedList 上的 removeFirst() remove(0) 之间的区别?

Difference between removeFirst() remove(0) on the LinkedList?

我正在尝试 return 并从 LinkedList 中删除第一个元素。以下是我能看到的两个选项。

第一种方法:

LinkedList<String> servers = new LinkedList<String>();
....
String firstServerName = servers.removeFirst();

第二种方法

List<String> servers = new LinkedList<String>();
....
String firstServerName = servers.remove(0);

return 并从 Java 中的链表中删除第一个元素的最有效方法是什么?我需要在我的 LinkedList 上更频繁地执行此操作。

您可以自己从源代码中比较它们(例如这里:http://developer.classpath.org/doc/java/util/LinkedList-source.html)。

removeFirst() 实现为:

 260:   /**
 261:    * Remove and return the first element in the list.
 262:    *
 263:    * @return the former first element in the list
 264:    * @throws NoSuchElementException if the list is empty
 265:    */
 266:   public T removeFirst()
 267:   {
 268:     if (size == 0)
 269:       throw new NoSuchElementException();
 270:     modCount++;
 271:     size--;
 272:     T r = first.data;
 273: 
 274:     if (first.next != null)
 275:       first.next.previous = null;
 276:     else
 277:       last = null;
 278: 
 279:     first = first.next;
 280: 
 281:     return r;
 282:   }

remove(int) 实现为:

575:   /**
 576:    * Removes the element at the given position from the list.
 577:    *
 578:    * @param index the location of the element to remove
 579:    * @return the removed element
 580:    * @throws IndexOutOfBoundsException if index &lt; 0 || index &gt; size()
 581:    */
 582:   public T remove(int index)
 583:   {
 584:     checkBoundsExclusive(index);
 585:     Entry<T> e = getEntry(index);
 586:     removeEntry(e);
 587:     return e.data;
 588:   }

 156:   /**
 157:    * Remove an entry from the list. This will adjust size and deal with
 158:    *  `first' and  `last' appropriatly.
 159:    *
 160:    * @param e the entry to remove
 161:    */
 162:   // Package visible for use in nested classes.
 163:   void removeEntry(Entry<T> e)
 164:   {
 165:     modCount++;
 166:     size--;
 167:     if (size == 0)
 168:       first = last = null;
 169:     else
 170:       {
 171:         if (e == first)
 172:           {
 173:             first = e.next;
 174:             e.next.previous = null;
 175:           }
 176:         else if (e == last)
 177:           {
 178:             last = e.previous;
 179:             e.previous.next = null;
 180:           }
 181:         else
 182:           {
 183:             e.next.previous = e.previous;
 184:             e.previous.next = e.next;
 185:           }
 186:       }
 187:   }

如果您只想删除 FIRST ELEMENT,请使用 LinkedList::remove():

E remove()

This method retrieves and removes the head (first element) of this list.

因此,您的最佳实践是:

String firstServerName = servers.remove();

removeFirst():删除列表中的第一个元素。 -> O(1)

remove(index):从列表中删除给定位置的元素。 -> O(n)

因此,在您的情况下,因为您只想删除第一个元素,所以您可以选择 removeFirst()