如果你使用的是LinkedList,你可以只使用 getFirst() 和 getLast() 来访问第一个元素和最后一个元素(如果你想要一个比size()更简洁的方法,那么得到(0))

实施

声明LinkedList

LinkedList mLinkedList = new LinkedList<>();

然后这是你可以用来获得你想要的方法,在这种情况下我们讨论的是列表的 FIRST 和 LAST 元素

/**

* Returns the first element in this list.

*

* @return the first element in this list

* @throws NoSuchElementException if this list is empty

*/

public E getFirst() {

final Node f = first;

if (f == null)

throw new NoSuchElementException();

return f.item;

}

/**

* Returns the last element in this list.

*

* @return the last element in this list

* @throws NoSuchElementException if this list is empty

*/

public E getLast() {

final Node l = last;

if (l == null)

throw new NoSuchElementException();

return l.item;

}

/**

* Removes and returns the first element from this list.

*

* @return the first element from this list

* @throws NoSuchElementException if this list is empty

*/

public E removeFirst() {

final Node f = first;

if (f == null)

throw new NoSuchElementException();

return unlinkFirst(f);

}

/**

* Removes and returns the last element from this list.

*

* @return the last element from this list

* @throws NoSuchElementException if this list is empty

*/

public E removeLast() {

final Node l = last;

if (l == null)

throw new NoSuchElementException();

return unlinkLast(l);

}

/**

* Inserts the specified element at the beginning of this list.

*

* @param e the element to add

*/

public void addFirst(E e) {

linkFirst(e);

}

/**

* Appends the specified element to the end of this list.

*

*

This method is equivalent to {@link #add}.

*

* @param e the element to add

*/

public void addLast(E e) {

linkLast(e);

}

那么,你可以使用

mLinkedList.getLast();

获取列表的最后一个元素 .

Logo

汇聚全球AI编程工具,助力开发者即刻编程。

更多推荐