Equivalent of std::vector in Java?

0 votes
asked Sep 16, 2010 by jmasterx

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 constructor and then pushBack, popBack() and that is stored in continuous memory (not linked list).


9 Answers

0 votes
answered Sep 16, 2010 by nikita-rybak

Everything's stored in array ("continuous memory") internally, although operation names are a bit different.

A bit more about list implementations in Java
And about generics

Helper Method also mentioned useful class in his answer (although not exactly equivalent to C++ Vector).

0 votes
answered Sep 16, 2010 by jaime-garcia

Java has Stack which supports push and pop. (http://download.oracle.com/javase/6/docs/api/java/util/Stack.html)

0 votes
answered Sep 16, 2010 by genia-s

Is ArrayList what you're looking for?
ArrayList l = new ArrayList<String>();
So you can have a list of anything (defined between the <>).

0 votes
answered Sep 16, 2010 by helpermethod

That would probably be ArrayDeque, if you need Stack functionality.

Do not use the Stack class as other here suggest.

0 votes
answered Sep 16, 2010 by colin-hebert

You can use an ArrayDeque, it doesn't support random access but support Deque (double ended queue) methods

0 votes
answered Sep 16, 2010 by guillaume-bodi
0 votes
answered Sep 16, 2010 by eamon-nerbonne

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.

0 votes
answered Sep 2, 2013 by cabumtz

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.

0 votes
answered Sep 15, 2017 by ahmed-elghareb

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() 
Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
Website Online Counter