Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

This is for ordered collections e.g. java.util.List. Why did the language designers not include a last method? The only reasons I can think of are:

  • ambiguity when the collection is empty (return null or throw exception)
  • API bloat

Any other reasons?

share|improve this question

closed as primarily opinion-based by Jarrod Roberson, MichaelT, gnat, Giorgio, GlenH7 Dec 9 at 20:06

Many good questions generate some degree of opinion based on expert experience, but answers to this question will tend to be almost entirely based on opinions, rather than facts, references, or specific expertise.If this question can be reworded to fit the rules in the help center, please edit the question.

7  
+1 for the sheer number of times that I've had to write collection.get(collection.size() - 1). –  jprete Apr 19 '11 at 19:51
1  
Why not write your own utility class that has this method, and any other method you might want to use with collections? –  Mahmoud Hossam Apr 19 '11 at 19:54
7  
There isn't a first() method either, so why should there be a last() method? –  Peter Taylor Apr 19 '11 at 20:37
5  
@Peter urgh the only thing worse than not implementing getLast() is implementing it with a hack like get(-1). –  Alb Apr 19 '11 at 23:12
2  
@Alb I guess "hack" is in the eye of the beholder :) At this point in time, I appreciate python's -1 syntax. Of course, if you ask me again sometime in the future or in the past, I may feel exactly as you do. –  three-cups May 10 '12 at 3:51

8 Answers 8

up vote 11 down vote accepted

API bloat is probably the answer. From my experience the only time I've needed this functionality a Queue or Stack was the correct data structure for the job having the appropriate method.

share|improve this answer
    
Guess you are partially correct, but if Java supported get(-1) to retrieve from the end of a list it would do what the OP wanted without adding API bloat. My answer as such has drawn unexplained downvotes. –  user949300 Dec 7 at 23:09

Not so sure about the API bloat issue, since other languages support get(-1) for this use, with no additional API at all.

share|improve this answer
    
Another reason to not support something like a last() method - infinite lists. –  Clockwork-Muse Dec 7 at 8:55
    
What's with the downvotes? Since this answer more or less refutes the "accepted answer", downvoters should explain themselves. What would be the problem with Java supporting get(-1) to retrieve the last element instead of get(list.size()-1)? get(-2) is second from the end, etc... –  user949300 Dec 7 at 23:06
    
I didn't downvote, but the problem is that your idea is an increase in the surface area of an API (which can lead to bloat). Unlike some other languages, List in Java is an interface, which means you have to be really careful about what the default behaviour is; counting 'backwards' prevents the use of things like infinite lists (which you could use to hold random numbers, say).... Also, the fact that this is an old question (and potentially subjective) might have factored into it. –  Clockwork-Muse Dec 8 at 0:45
    
Could you elaborate on "infinite lists"? Since List.get() take an int, and even today's huge computers don't have infinite memory, the idea makes no sense to me. –  user949300 Dec 8 at 2:24
    
When it comes to List, generally you're going to use an Iterator (either explicitly, or implicitly via things like for-each) to read through elements - it's trivial to make these reference infinite/looping elements. Having an 'infinite' list doesn't mean you're actually storing that much data, just that there's an element accessible, somehow. Consider a list containing the digits of 1 / 3 (perhaps as part of a Natural/Rational number library). There is no last digit - it's trivial to say what each digit will be - 3 - but you can neither store them individually, nor get a last. –  Clockwork-Muse Dec 8 at 10:05

The java.util.LinkedList defines the getLast() and getFirst() methods. Unfortunately these methods are not defined in one of it's interfaces, so you have to use the LinkedList type. If you are only interested in the last element you might consider to use the java.util.Queue interface's peek() method. LinkedList implements Queue.

share|improve this answer

a last() method is just as easy as list.get(list.size()-1), just like there is no first() method or fifth() method. It isn't that hard to synthesize and is a specialization. You can also reverse() the list and list.get(0) which will give the last item. Things that are easy to do, usually don't get their own specialized methods.

import java.util.ArrayList;
import java.util.List;

public class Main
{
    public static void main(String[] args)
    {
        final List<String> l = new ArrayList<String>();

        l.add("A");
        l.add("B");
        l.add("Z");

        System.out.println("l.get(0) = " + l.get(0));
        System.out.println("l.get(l.size()-1) = " + l.get(l.size() - 1));
    }
}

results in the following output

l.get(0) = A
l.get(l.size()-1) = Z

it is also presumptuous to assume that everything that implements the List interface actually has the concept of last() anything.

share|improve this answer
1  
It would be clearer in both cases though –  Anto Apr 19 '11 at 19:56
    
Note that the size() method may not be able to answer if the collection is not yet fully populated. –  user1249 Apr 20 '11 at 10:37
1  
.size() will return the current size .size()-1 will still be the last element regardless, how would it know if it was fully populated or not? –  Jarrod Roberson Apr 20 '11 at 18:15
1  
By the specification, a List can contain more than Integer.MAX_VALUE elements, in which case size() returns Integer.MAX_VALUE, so .size()-1 is not the perfect way to implement last() (though such a large list is very unlikely and I wonder how such a list would implement toArray()...) –  user281377 May 9 '12 at 9:52
1  
C# does have a .First & .Last method. Reversing a list just to get the last item isn't exactly efficient either. –  Carra Feb 6 '13 at 13:06

As others have said, it's probably because they didn't want to bloat the interface.

You could use java.util.Deque which is implemented by java.util.LinkedList or java.util.ArrayDeque. Your trading in random access, though. Deque has getFirst() and getLast() and you'd still be programming against an interface.

share|improve this answer

Because Gosling was a LISP programmer (and always expected lisp processing to go by 'cdr')?

Kind of a flip answer, but what are you going to use a generic list for? If you're really going to be accessing the last element a lot, do you really want a generic data type like List? You'd be signing up for whatever performance horriblenesses there are in, say, a singly-linked list.

I'd think List was a minimal-functionality type, not a maximal-functionality type.

share|improve this answer
4  
I doubt that James Gosling himself designed the collections API. As far as I know most of that has been designed by Joshua Bloch. –  Jesper May 9 '12 at 10:13

What meaning does last() (or first(), for that matter) have with a Set or any other possible future collection other than a List?

And in practice, how often are you likely to call that method on a List?

share|improve this answer
1  
I debated that second sentence. I'm sure that some people want to look at the last element in a list and ignore all the others. But I suspect that most of them shouldn't be using a List –  Anon Apr 19 '11 at 20:50
2  
The question specifically said ordered collections. –  Alb Apr 19 '11 at 21:03
    
The question isn't just about List. last() and first() would make sense for SortedSet and other ordered collections. –  Andres F. May 9 '12 at 12:24

Basically you either have to ask for the size() for a for-loop or iterate it by asking for its iterator and use it in a while or do-loop. Use the one suitable for your purpose.

The iterator knows at a given point if there are more entries and allows you to get the next one if there is. You then repeat until "more entries?" fails.

See the "Traversing Collections" section at http://download.oracle.com/javase/tutorial/collections/interfaces/collection.html

share|improve this answer

protected by MichaelT Dec 7 at 3:39

Thank you for your interest in this question. Because it has attracted low-quality answers, posting an answer now requires 10 reputation on this site.

Would you like to answer one of these unanswered questions instead?

Not the answer you're looking for? Browse other questions tagged or ask your own question.