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).
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()
Related
I have to write a stack for class and while I understand the concept of how a stack works, I wasn't told if they are made using an array or a linked list or something else? How are most stacks created?
ArrayDeque is a solid class implementation of the stack concept. This class has implemented stack in the most efficient way. Please look at the class implementation for the details of various methods.
http://www.docjar.com/html/api/java/util/ArrayDeque.java.html
More specifically, look at public E pollFirst(){...} and public void addFirst(E e)
java.util.Stack is a subclass of java.util.Vector which was a Thread-safe precursor to ArrayList. Hope that helps.
Both options, array and linked list are appropiate.
A linked list may be simpler because you needn't worry about the array size. An array based implementation on the other hand may have better runtime behavior and can be easier to debug (because its easier to view the array than a linked list in the debugger).
Chose whatever you're comfortable with.
First I should say that in my book (2005), Vector<E> is (extensively used) in place of arrays. At the same time there is no explanation with differences between the two. Checking the Oracle Doc for Vector class it's pretty easy to understand its usage.
Doing some additional research on StackOverflow and Google, I found that the Vector class is actually deprecated and to use ArrayList instead, is this correct? I also found an extensive explanation about differences between Array and ArrayList.
The part that I can't really understand: Is there a rule on where I should use ArrayList instead of simple arrays? It seems like I should always use ArrayList. It looks more efficient and should be easier to implement collections of values/objects, is there any down side with this approach?
Some history:
Vector exists since Java 1.0;
the List interface exists since Java 1.2, and so does ArrayList;
Vector has been retrofitted to implement the List interface at that same time;
Java 5, introducing generics, has been introduced in 2004 (link).
Your course, dating back 2005, should have had knowledge of ArrayList at the very list (sorry, least), and should have introduced generics too.
As to Array, there is java.lang.reflect.Array, which helps with reflections over arrays (ie, int[], etc).
Basically:
Vector synchronizes all operations, which is a waste in 90+% of cases;
if you want concurrent collections, Java 5 has introduced ConcurrentHashMap, CopyOnWriteArrayList etc, you should use those;
DO NOT use Vector anymore in any event; some code in the JDK still uses it, but it is for backwards compatibility reasons. In new code, there are better alternatives, as mentioned in the previous point;
since Java 1.2, Vector does not offer the same thread safety guarantees as it used to offer anyway.
The latter point is interesting. Prior to Iterator there was Enumeration, and Enumeration did not offer the possibility to remove elements; Iterator, however, does.
So, let us take two threads t1 and t2, a Vector, and those two threads having an Iterator over that vector. Thread t1 does:
while (it.hasNext())
it.next();
Thread t2 does:
// remember: different iterator
if (!it.hasNext())
it.remove();
With some unlucky timing, you have:
t1 t2
------ ------
hasNext(): true
.hasNext(): false
removes last element
.next() --> BOOM
Therefore, Vector is in fact not thread safe. And it is even less thread safe since Java 5's introduction of the "foreach loop", which creates a "hidden" iterator.
The basic difference between an array and an ArrayList is that an array has fixed size, whereas, ArrayList can dynamically grow in size as needed. So, if you are assured that your array size won't change, then you can use it. But if you want to add elements later then a an ArrayList which is an implementation of List interface, is the way to go.
Although an ArrayList is internally backed by an array only. So, internally it also uses a fixed size array, with an initial capacity of 10 (which can change for that matter), but that detail is internally hidden. So, you don't have to bother about the changing size of the ArrayList.
Whenever you add elements more than the current size of array in your ArrayList, the internal array is extended. That means, the regular expansion of size can become an overhead, if you are regular inserting a large number of elements. Although this is rarely the case. Still, you can also give your own initial size while creating an ArrayList. So, that's upto you to decide.
As for Vector vs ArrayList discussion, yes Vector is now deprecated (not technically though, but it's use is discouraged as stated in comments by #Luiggi), and you should use an ArrayList. The difference is that Vector synchronizes each operation, which is nearly never required. When you need synchronization, you can always create a synchronized list using Collections.synchronizedList.
For more on this discussion, see this post.
An ArrayList is an implementation of List. There are other variations too. Like you also have a LinkedList, to get the functionality of a traditional linked list.
Vector Class is actually deprecated and to use ArrayList instead, is this correct?
Yes this is correct. Vector class and some other collections are deprecated and replaced with new collections like ArrayList, Map, etc. Here are few reasons why Vector is deprecated
Is there a rule on where i should use ArrayList instead of simple Arrays?
Almost always. I can think of two reasons why you should use arrays:
Makes JNI calls easier. It is MUCH easier to send a simple array from C++ to Java than an object of ArrayList
You can gain a little bit of performance, since access to elements of simple array does not requires boundaries checks and method calls.
On other hand using ArrayList gives a lot of advantages. You do not need to think about controlling array's size when you add new element, you can use simple API of ArrayList for adding/removing elements from your collection, etc.
I'll just add my two cents.
If you need a collection of primitive data and optimization matters, arrays will always be faster, as it eliminates the requirement of auto-boxing and auto-unboxing.
In C++, iterators in STL is very useful. I can write container independent code to process sequences.
However, I found Iterator and ListIterator are very poor in Java. They even don't support clone(). I think it's impossible to process sequences with them.
The only way to do this seems to be using arrays forever, but how can I reuse my code when I change arrays to Lists ?
Processing sequences is to do some algorithms on a sequences of Objects. For example, sorting them , finding the maximun, remove duplicated items.
List<Type> list = new List<Type>
//add the elements...
for(Type t : list)
//do you stuff with t
Normally you will not need to use the iterators explicitly in Java. Also, be careful with .clone() as it is rarely the most appropriate solution.
List itself is a interface that is implemented by different containers.
I would use List<Type>, and avoid clone() as it doesn't always do what you think. i.e. it can be shallow or deep depending on the implementation.
List is a basic class. Perhaps if you give an example of what you are having trouble with it we can help you with that.
I always learn when we declare a collection we should do, Interface ob = new Class(), if i want to use for example a LinkedList i'll do List ob = new LinkedList(), but then i can't have access to all methods from LinkedList.. Isn't LinkedList ob = new LinkedList() 100% correct?
Isn't LinkedList ob = new LinkedList() 100% correct?
Well I'd suggest using the generic form, but sure - if you want to use functionality which is specific to LinkedList, you need to declare the variable accordingly.
You might want to check whether the Deque<E> or Queue<E> interfaces have what you want though. If they do, use those in-keeping with the idea of describing what you need rather than what implementation you'll use.
Yes,
LinkedList<...> items = new LinkedList<...>();
is perfectly correct if you know that items will depend on methods of LinkedList<T> that are not captured in the List<T> interface.
You should always try to keep the declaration at the highest level possible, meaning that you should stop at the highest level that provides all the functionality that you need: if List methods are not enough, you're perfectly fine with your LinkedList declaration.
If you actually have a need to use methods that are not on the List interface, there is certainly nothing wrong with using LinkedList's API. The general rule of programming to the List interface recognizes that 1) it's pretty rare to need those methods, and 2) in most people's experience, it's way more likely that I discover I need to sort the list and/or use a lot of random access, and decide to switch to an ArrayList, than it is I need one of the methods only LinkedList has.
It may be also that you could be programming to the Queue interface, if you find List isn't giving you what you need.
The rule "always code to interfaces" must be taken with some flexibility. What you are suggesting is fine, and as you came to the conclusion, the only option.
As a side note, coding to concrete classes like this is faster is most JVMs. Deciding whether the performance is worth breaking the rule is the hard thing to decide.
LinkedList is a generic. You should be doing:
LinkedList<String> linkedList = new LinkedList<String>();
(or whatever else you need to store in there instead of String)
Not exactly 100% correct.
A preferred way to declare any collection is to include the data type it's holding. So, for your example, it'd be LinkedList<Integer> ob = new LinkedList<Integer>();.
Nope.. This would be wrong, at the later stages if he wants to change his implementation from linked list to any other implementation of list type he will go wrong... So better to use the interface level declaration.
I won't always suggest you to use generics .....
Coz sometimes you may need to wrap different objects as here....
String str="a string";
boolean status=false;
LinkedList ll = new LinkedList();
ll.add(str);
ll.add(status);
In some situations like case of RMI, u can only send serialized data.....and suppose you want to send a class object(which is unserialized).......There you can wrap the members of the class(primitives) in a LinkedList and pass that object as a whole.......not worrying about the huge number of arguments......
Consider for eg:
public Class DataHouse
{
public int a;
public String str;
.
.
.
}
Now Somewhere u need to pass the objects....
You can do the following....
DataHouse dh =new DataHouse();
LinkedList ll = new LinkedList();
ll.add(dh.a);
ll.add(dh.str);
// Now the content is serialized and can pass it as a capsuled data......
you can still have access to LinkedList methods by using List, all you have to do is to type cast
for example
((LinkedList)ob).add()
The point of using generic List and not LinkedList is because in case you simply change the type of lists you are using (let's say double linked list) your program will still work Generics are to simplify your code to be more portable and more "changeable"
Actually it would be better if it would be parametrized as both are raw types.
I have the following problem in my Data Structures and Problem Solving using Java book:
Write a routine that uses the Collections API to print out the items in any Collection in reverse order. Do not use a ListIterator.
I'm not putting it up here because I want somebody to do my homework, I just can't seem to understand exactly what it is asking for me to code!
When it asks me to write a 'routine', is it looking for a single method? I don't really understand how I can make a single method work for all of the various types of Collections (linked list, queue, stack).
If anybody could guide me in the right direction, I would greatly appreciate it.
Regardless from the question not making much sense as half of the collections have no gstable ordering of have fixed-ordering (i.e. TreeSet or PriorityQueue), you can use the following statement for printing the contents of a collection in reverse-natural order:
List temp = new ArrayList(src);
Collections.reverse(temp);
System.out.println(temp);
I essence you create an array list as lists are the only structure that can be arbitrarily reordered. You pass the src collection to the constructor which initializes the list withj the contents of the src in the collection natural order. Then you pass the list to the Collections.reverse() method which reverses the list and finally you print it.
First, I believe it is asking you to write a method. Like:
void printReverseList(Collection col) {}
Then there are many ways to do this. For example, only using the Collection API, use the toArray method and use a for loop to print out all the items from the end. Make sense?
As for the various classes using the Collection interface, it will automatically work for all of those since they must implement the interface (provided they implement it in a sane way;).
Well you could have a routine that delegates to other routines based on the input type, however I'm not sure there is a generic enough collection type that can be encompassed into one argument. I guess you could just use method overloading (having multiple methods with the same name, but accept different args).
That could technically count as 1 routine (all have the same name).
I don't know much Java, but considering the "Collections API" i imagine all those objects implement an interface you could iterate through someway. i suppose they all could have an itemAtIndex( int index ) and length() or similar method you could use.
You might want to read this.
Isn't there a base Collection class?
Probably worth looking here as a starting point: Collections.