Java equivalent of std::deque

2020-02-05 14:07发布

I'm a relatively new Java programmer coming from C++/STL, and am looking for a class with these characteristics (which the C++ std::deque has, as I understand it):

  1. O(1) performance for insertion/removal at the beginning/end
  2. O(1) performance for lookup by index
  3. are growable collections (don't need fixed size bounds)

Is there a Java equivalent to this? I found the Java 1.6 [ArrayDeque] class which has the insert/removal and growable characteristics, but don't seem to have lookup-by-index unless you call toArray() which would not be O(1).

4条回答
SAY GOODBYE
2楼-- · 2020-02-05 14:35

Primitive Collections for Java has an ArrayDeque with a get(int idx) method.

http://sourceforge.net/projects/pcj

I can't vouch for the quality of this project though.

An alternative would be to get the JDK ArrayDeque source and add the get(int idx) method yourself. Should be relatively easy.

EDIT: If you intend to use the deque in a highly multi-threaded manner, I would go the "patch the JDK's ArrayDeque" route. This implementation has been tested thoroughly and is used in the new java.util.concurrent ForkJoin framework.

查看更多
再贱就再见
3楼-- · 2020-02-05 14:36

Here is a ready-to-use circular buffer implemented in Java, CircularArrayList. It isn't growable after creation, though. (Disclaimer: This link points to my own website)

The other option floating around the web would be the one from the Java Specialists Newsletter. I never used that one, for the following reasons:

  1. It is incomplete - ("This method left as an exercise to the reader")
  2. It does not support generic element type as would have been consistent with other collections from the Java Collection's Framework.
  3. It is unnecessarily complicated, and therefore possibly buggy, instead of following the extension procedure recommended by AbstractList's Javadoc.
查看更多
再贱就再见
4楼-- · 2020-02-05 14:49

Interesting... I was just finishing reading Java Generics and Collections and it has a brief discussion of this kind of collection including a link to the Java Specialists' Newsletter which includes a CircularArrayList that might do what I need.

查看更多
贪生不怕死
5楼-- · 2020-02-05 14:58

My default approach would be to hack together my own class, with ArrayList as an underlying implementation (e.g. map my own class's indices to ArrayList indices)... but I hate reinventing the wheel especially when there's a good chance of screwing up...

查看更多
登录 后发表回答