views:

742

answers:

4

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).

+8  A: 

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.

bajafresh4life
Source for GNU classpath ArrayDeque is here: http://fuseyism.com/classpath/doc/java/util/ArrayDeque-source.html. It should be reasonably easy to add get(i), or even to make it implement List<E>
tgamblin
PCJ only works for primitive types, which rather limits its usefulness.
Michael Myers
Interesting... The GNU stuff scares me (although the license for the ArrayDeque code you list shows Creative Commons... strange) because I'm working in a commercial environment and can't use any GPL code.
Jason S
You can use the JSR166 backport at:http://backport-jsr166.sourceforge.net/It's released into the public domain; no licensing issues.
bajafresh4life
A: 

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...

Jason S
I deleted my post about HashMap, but it would be an improvement over ArrayList for arbitrary insertions I think.
Daddy Warbox
A: 

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.

Jason S
+1  A: 

(comment removed by author)