我正在尝试返回并从LinkedList中删除第一个元素。以下是我可以看到的两个选项。
第一种方法:
LinkedList<String> servers = new LinkedList<String>();
....
String firstServerName = servers.removeFirst();
第二种方法
List<String> servers = new LinkedList<String>();
....
String firstServerName = servers.remove(0);
在Java中从链表中返回和删除第一个元素的最有效方法是什么?我需要在LinkedList上更频繁地执行此操作。
答案 0 :(得分:4)
removeFirst()
:删除列表中的第一个元素。 - &GT; O(1)
remove(index)
:从列表中删除给定位置的元素。 - &GT;为O(n)
因此,在您的情况下,因为您只想删除第一个元素,您可以选择removeFirst()
。
答案 1 :(得分:2)
您可以从源代码中自行比较它们(例如: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 < 0 || index > 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: }
答案 2 :(得分:0)
如果你想要的只是删除FIRST ELEMENT,请使用LinkedList::remove():
E remove()
此方法检索并删除此列表的头部(第一个元素)。
因此,您的案例中的最佳做法是:
String firstServerName = servers.remove();