Search code examples
javacollections

Java List addressing first and last elements


Is there any better way to access the first and last locations on a java list other than

curr.set(curr.size()-1, 10);
curr.get(curr.size()-1);
curr.set(0, 10);
curr.get(0);

Where curr can be assumed to be a list.


Solution

  • If you use LinkedList you can get the last and first elements.

    LinkedList<String> linkedList = new LinkedList<>();
    linkedList.add("element");
    
    String last = linkedList.getLast();
    String first = linkedList.getFirst();
    

    Both operations are constant time, but a NoSuchElementException will be thrown if the list is empty.