Where can I find a documentation Vector and Hashtable in Java? - java

I know this question can be a little stupid but I just want to clear the doubt.
When going through Java tutorial for Collection ( http://docs.oracle.com/javase/tutorial/collections/index.html ), I didn't find any relevant information about both Vector and Hashtable. Both belong to Collection framework as Vector is implementation of List and Hashtable is implementation of Map. If it is so then why it is not in Sun tutorial? Where can I find Sun tutorial for Collection which contain good doc about both Vector and Hashtable and in depth knowledge about elements storing in List, Set and Map?

Because Vector and Hashtable are old, legacy collection classes. Don't use them.
Instead of Vector use ArrayList; instead of Hashtable use HashMap.
When Java 1.2 was released (very long ago), new collection classes were added to Java (the Collections Framework). Sun did not remove the old classes such as Vector and Hashtable because they wanted the new Java version to be backwards compatible. And now we still have those old classes.
One difference to be aware of is that Vector and Hashtable are synchronized, while ArrayList and HashMap are not. Most of the time you don't need synchronization; if you do, then you must take care to synchronize your ArrayList, and if you need a map, use ConcurrentHashMap instead of plain HashMap.

In general, Vector and Hashtable could be considered deprecated.
If you look at the online javadoc for Vector and Hashtable you'll see that they were the original implementation of ArrayList and HashMap, until the Collections framework came along, at which point they were retrofitted to implement interfaces from the Collections framework; this way, old classes that depended on those classes being there would not break. The only difference between them and their more common brethren is that they are synchronized.
In the vast majority of cases, synchronization isn't called for, so programmers will avoid the synchronization overhead and opt for regular ArrayLists and HashMaps. If a synchronized collection is desired there's always Collections.synchronized____() (or ConcurrentHashMap) that would work just fine too.
You probably don't need a tutorial for Vector and Hashtable because their behavior is already so similar to classes you're likely to be familiar with, and because they aren't used much any more. As for more info on List, Set, and Map, the online javadoc is a good place to start.

here are useful links for you
http://javarevisited.blogspot.com/2010/10/difference-between-hashmap-and.html
http://javarevisited.blogspot.com/2011/09/difference-vector-vs-arraylist-in-java.html

As mentioned by the JavaDoc of Vector:
As of the Java 2 platform v1.2, this class was retrofitted to implement the List interface, making it a member of the Java Collections Framework. Unlike the new collection implementations, Vector is synchronized. If a thread-safe implementation is not needed, it is recommended to use ArrayList in place of Vector.
it is kind of a legacy implementation of the List interface. The whole collection framework has been implemented to be by default not thread-safe. If you need thread safety, you may wrap any non tread-safe implementation by using the proper Collections.synchronizedXXX() methods, where XXX is List or Map or Set for example. The same applies for HashTable, which is by default synchronized as well. You should use HashMap instead and Collections.synchonizedMap() instead.

Related

Difference between map and ImmutableMap

I work in payment gateway company and while analyzing the code I came across
ImmuatbleMap objects. I want to know all the details about. What is it?
What are its advantages over the map? Does core java has its support for ImmuatbleMap?
ImmutableMaps are introduced in Guava, they comply to Java's Map API, but with additional guarantees.
In a nutshell:
you cannot add, replace or remove entries
they are "fully immutable" if entry objects do not have mutable state
as a consequence, they are thread safe
nulls are forbidden
(slightly) more time- and space-efficient compared to usual Java's collections
iteration order is predictable
For full info see Guava's guide and javadoc for ImmutableCollection which applies to maps and other Guava's immutable collections.

is there any scenario where hashtable is better than concurrenthashmap?

As we all know that ConcurrentHashMap is better in performance but can we have any scenario where Hashtable is better?
I'll say this before answering the question: do not ever use Hashtable anymore. Hashtable is a legacy tool from Java 1.0, before the superior collections framework introduced with Java 2 going onwards.
If you require a simple hash map, use HashMap. If you require performing thread-safety, use ConcurrentHashMap. If you require plain basic and non-performing thread-safety, wrap a HashMap into Collections.synchronizedMap(Map).
Now to actually answer the question as is, which is purely compare two specific classes without seeing the spectrum of possibilities:
Yes, such scenarios exist
From the Hashtable documentation:
If a thread-safe implementation is not needed, it is recommended to use HashMap in place of Hashtable. If a thread-safe highly-concurrent implementation is desired, then it is recommended to use ConcurrentHashMap in place of Hashtable.
So yes, Hashtable is appropriate for scenarios where you need a thread-safe implementation, but do not "desire" a highly-concurrent implementation. This, again strictly in the exclusive comparison between ConcurrentHashMap and Hashtable.
Also, if you need Enumeration[1], Hashtable has a direct support, while you have to go through Collections.enumeration(...) for other Maps.
1. Enumeration is also a Java 1.0 class. Switch to Iterator (if using Java 2 to 7) or Stream (if using Java 8+)

java: difference between map and hash table

I don't understand this code Map<E, Integer> d = new HashTable<E, Integer>(list.size()); : we create a new object but is it a map or a hashtable? what is the difference between the both of them? I thought that a map is just a way to put 2 element together like a key and its value (for exemple {3; Detroit})
is it a map or a hashtable?
Yes.
The static, compile time type of the reference is Map. As others have already pointed out, it's an interface. You can call all the methods on the Map interface and know that they'll obey the contract and behave as describe.
The dynamic, run time type of the object reference refers to is Hashtable. It implements all the methods in the Map interface in its own way.
The key idea is that the compile time type of a reference is separate from the run time type of the object on the heap that it points to.
Hashtable is a JDK 1.0 class that sticks around for compatibility reasons. It's been retrofitted to implement the Map interface, which was introduced later. You'd be well advised to choose another implementation, such as HashMap, depending on your requirements.
The last part of Hashtable contains the reason why it should not be used:
As of the Java 2 platform v1.2, this class was retrofitted to implement the Map interface, making it a member of the Java Collections Framework. Unlike the new collection implementations, Hashtable is synchronized. If a thread-safe implementation is not needed, it is recommended to use HashMap in place of Hashtable. If a thread-safe highly-concurrent implementation is desired, then it is recommended to use ConcurrentHashMap in place of Hashtable.
This means that it is less efficient than HashMap for single-thread models and less efficient than ConcurrentHashMap for multi-threaded models.
Understanding how compile and run time types differ is crucial to understanding how object oriented polymorphism works. This is true for all OO languages: C++, Java, .NET, Python, etc.
Map is an interface. Hashtable is one of the classes that implements the Map interface.
See the Java Doc for the Map interface. Specifically the section that says all known implementing classes.
Any class that implements a Map provides a key->value data-structure. A Map being an interface defines the contract that all implementing classes must adhere to. By itself, a Map cannot be instantiated.
Note that while Hashtable should ideally have been named as HashTable following the java naming conventions, this is is a pre-historic class in Java which exists even before the standard java naming conventions came into existence. Therefore, it is still called Hashtable and not HashTable as wrongly mentioned in your question.
Map is an interface. HashTable is one implementation of that interface. There are several others, such as HashMap, SortedMap, etc. The interface defines the programming API; the implementation defines how that API is implemented. Different implementations may have different runtime performance characteristics.
With regard to interfaces vs. implementations, you may find my answer to Java - HashMap vs Map objects here helpful.

How can I change all my legacy Vectors to ArrayLists, and are there any caveats?

I have a medium-sized Java project in Eclipse, which uses Vector<E> instead of the preferred ArrayList<E>. I would like to replace those.
Is there any way, using Eclipse, to change all these? Any refactoring method?
Or would it be sufficient to do a general search-and-replace for every Vector<String> occurrence? Are there any caveats to this? What are situations in which this approach would fail?
Actually, I just did the latter, and it worked for my application, but this should be a more general question.
Vector was retrofitted to implement List in Java 1.2 when the Collections API, which includes ArrayList, was introduced. So it has both old-style methods like elementAt(), and new-style methods like get(), which are largely work-alike.
The old methods aren't in List or ArrayList, so if you searched and replaced, and were using old methods, it would fail to compile. Easy enough to find and fix those, though. Same for iterator()/Iterator replacing Enumeration and such.
Vector's operations were synchronized; if the program relied on that for correctness, it could fail if replaced with ArrayList, which is not. Wrap with Collections.synchronizedList() if you need the old behavior. This is a source of subtler bugs.
The only things that could make it go wrong are
if you use methods that are in Vector, but not in ArrayList (but I'm not even sure such a method exists)
if you're relying on the synchronized-ness of Vector in some of your classes to make them thread-safe.
if you use reflection somewhere and this reflection-based code uses the Vector class name.
if you use some legacy API still using Vector and not List of ArrayList (like some Swing classes)

Why is Java Vector (and Stack) class considered obsolete or deprecated?

Why is Java Vector considered a legacy class, obsolete or deprecated?
Isn't its use valid when working with concurrency?
And if I don't want to manually synchronize objects and just want to use a thread-safe collection without needing to make fresh copies of the underlying array (as CopyOnWriteArrayList does), then is it fine to use Vector?
What about Stack, which is a subclass of Vector, what should I use instead of it?
Vector synchronizes on each individual operation. That's almost never what you want to do.
Generally you want to synchronize a whole sequence of operations. Synchronizing individual operations is both less safe (if you iterate over a Vector, for instance, you still need to take out a lock to avoid anyone else changing the collection at the same time, which would cause a ConcurrentModificationException in the iterating thread) but also slower (why take out a lock repeatedly when once will be enough)?
Of course, it also has the overhead of locking even when you don't need to.
Basically, it's a very flawed approach to synchronization in most situations. As Mr Brian Henk pointed out, you can decorate a collection using the calls such as Collections.synchronizedList - the fact that Vector combines both the "resized array" collection implementation with the "synchronize every operation" bit is another example of poor design; the decoration approach gives cleaner separation of concerns.
As for a Stack equivalent - I'd look at Deque/ArrayDeque to start with.
Vector was part of 1.0 -- the original implementation had two drawbacks:
1. Naming: vectors are really just lists which can be accessed as arrays, so it should have been called ArrayList (which is the Java 1.2 Collections replacement for Vector).
2. Concurrency: All of the get(), set() methods are synchronized, so you can't have fine grained control over synchronization.
There is not much difference between ArrayList and Vector, but you should use ArrayList.
From the API doc.
As of the Java 2 platform v1.2, this
class was retrofitted to implement the
List interface, making it a member of
the Java Collections Framework. Unlike
the new collection implementations,
Vector is synchronized.
Besides the already stated answers about using Vector, Vector also has a bunch of methods around enumeration and element retrieval which are different than the List interface, and developers (especially those who learned Java before 1.2) can tend to use them if they are in the code. Although Enumerations are faster, they don't check if the collection was modified during iteration, which can cause issues, and given that Vector might be chosen for its syncronization - with the attendant access from multiple threads, this makes it a particularly pernicious problem. Usage of these methods also couples a lot of code to Vector, such that it won't be easy to replace it with a different List implementation.
You can use the synchronizedCollection/List method in java.util.Collection to get a thread-safe collection from a non-thread-safe one.
java.util.Stack inherits the synchronization overhead of java.util.Vector, which is usually not justified.
It inherits a lot more than that, though. The fact that java.util.Stack extends java.util.Vector is a mistake in object-oriented design. Purists will note that it also offers a lot of methods beyond the operations traditionally associated with a stack (namely: push, pop, peek, size). It's also possible to do search, elementAt, setElementAt, remove, and many other random-access operations. It's basically up to the user to refrain from using the non-stack operations of Stack.
For these performance and OOP design reasons, the JavaDoc for java.util.Stack recommends ArrayDeque as the natural replacement. (A deque is more than a stack, but at least it's restricted to manipulating the two ends, rather than offering random access to everything.)

Categories