Equivalent of std::vector in Java?
What would be the closest thing to a std::vector in Java? By this I mean, a class which can take in T into its开发者_JS百科 constructor and then pushBack, popBack() and that is stored in continuous memory (not linked list).
Thanks
ArrayList
Everything's stored in array ("contiguous memory") internally, although operation names are a bit different.
A bit more about list implementations in Java
And about generics
edit
Helper Method also mentioned useful class in his answer (although not exactly equivalent to C++ Vector).
That would probably be ArrayDeque, if you need Stack functionality.
Do not use the Stack class as other here suggest.
Is ArrayList what you're looking for?
ArrayList l = new ArrayList<String>();
So you can have a list of anything (defined between the <>).
You're probably looking for the ArrayDeque
which supports push/pop style access from both ends of the list efficiently.
Avoid Stack
and Vector
- these are synchronized, which implies generally pointless overhead.
ArrayList
is also fine; however, you'd need to implement your own (trivial) pop method since it is not provided by the class itself. ArrayList
does permit indexed access, which ArrayDeque
lacks.
You can use an ArrayDeque
, it doesn't support random access but support Deque
(double ended queue) methods
Java has Stack which supports push and pop. (http://download.oracle.com/javase/6/docs/api/java/util/Stack.html)
How about simply the Vector class?
http://download-llnw.oracle.com/javase/6/docs/api/java/util/Vector.html
What you need is exactly an java.util.ArrayList<T>
You can check the documentation in http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html
Basically is a List implemented with an Array where the references live in a continuous chunk of memory.
I recommend to use in combination with a interface variable like this: List<String> stringList = new ArrayList<String>();
so if you decide, you can change the implementation to java.util.LinkedList<T>
or another one.
i think it is the LinkedList
vector (c++) <===========> linkedlist(java)
v.front() <===========> l.peekFirst()
v.back() <===========> l.peekLast()
v.push_back(x) <===========> l.add(x)
v.pop_back() <===========> l.pollLast()
精彩评论