Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Collection

 
raj joe
Ranch Hand
Posts: 99
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When do i use

1.Vector or ArrayList ?
2.HashTable or HashMap ?
3.What should i do to get the objects in the collection in the same order as i put in.?
 
David Harkness
Ranch Hand
Posts: 1646
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hashtable and Vector are the original, synchronized collections. Even if you need a synchronized collection, I'd skip those and either use ArrayList/HashMap wrapped using Collections.synchronizedList/Map() or a collection specifically coded to do better synchronization. For example, JDK 1.5 has ConcurrentHashMap which allows multiple readers and only locks out other threads when writing. It has better multithreaded performance under average conditions (reads exceed writes).

List already maintains insertion order if you add items at the end. LinkedHashMap adds insertion-order-iteration to HashMap.
 
Nischal Tanna
Ranch Hand
Posts: 182
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
1.Vector or ArrayList ?
2.HashTable or HashMap ?
3.What should i do to get the objects in the collection in the same order as i put in.?


As 1. Use Vector when u want ur Collection object to be thread safe (safe while multiple threads invoking operations which JVM achieves by having Object level lock. No chances of data getting corrupted in the Vector). Use ArrayList when thread safety dosent matter to u (Chances of data getting corrupted if multiple threads working on the same reference).

As 2. same as above (Hashtable-thread safe, HashMap - not thread safe. Additionaly Hashtable does not permit any null key and null value, however HashMap permits single null key and null values)

As3. use LinkedHashMap,LinkedHashSet,LinkedList,Vector,ArrayList
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here's a Collections Crib Sheet I made because I couldn't keep them all in my head. The Collections class has some factory methods that return thread safe versions of collections and other specialized versions.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic