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?
|
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:
Any other reasons? |
|||
| show 2 more comments |
|
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. |
|||
|
|
|
a
results in the following output
|
|||||||||||||||||
|
|
Basically you either have to ask for the 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 |
|||
|
|
|
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 interessted in the last element you might consider to use the java.util.Queue interface's peek() method. LinkedList implements Queue ;) |
|||
|
|
|
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. |
|||||
|
|
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. |
||||
|
|
|
What meaning does And in practice, how often are you likely to call that method on a |
|||||||||||
|
collection.get(collection.size() - 1). – jprete Apr 19 '11 at 19:51