Hacker News new | ask | show | jobs
by benrow 1339 days ago
At first glance, one might think Java already has collection types with defined encounter order - List (defined iteration order based on insertion order) and SortedSet/SortedMap (defined iteration order based on elements implementing the Comparable interface).

Reading more carefully, the proposal aims to lift the sequenced type higher up the hierarchy, so client code doesn't need to code to specific implementations.

So far, operations available on collection types are influenced by the implementation. So what happens if I call the proposed addFirst() on an ArrayList, rather than a LinkedList? For the former case, I doubt all the elements will get shifted up by one, so would it create a new underlying array?

(Edit: of course it would, the underlying array is recreated for resize operations already. But it would involve a slow array copy operation for what may be a common case operation). I guess my point here is, if you lift operations into a common super-type some of those operations may have implementation challenges for some subtypes.

(Edit 2: turns out it's already possible to insert an element at the head of an ArrayList using add(0, foo) so there's no change to supported methods, just an abstraction of existing APIs, as far as I can tell).

1 comments

List lacks simple methods to access the head and tail. There are multiple times I wanted to get the tail element but had to do two calls (get size and get(size-1)). Having first()/last() methods would make it easy and more readable.
On the other hand the way the interfaces are layered is not ideal, because the implications of e.g. `removeFirst` and `removeLast` for an arraylist are very different from a linked list.

Or getLast on an arraylist (or doubly linked list) versus singly linked.

Nit: "tail" usually means "everything except the head", not "last element". I got a little confused there for a moment reading your comment.
Doesn't java libs have a deq - a double-ended queue?
Yes, Java has java.util.Deque [1]. The purpose of this JEP is to add a more generic interface over the ordered collection types, which all have slightly different names for these operations.

[1] https://docs.oracle.com/en/java/javase/17/docs/api/java.base...