Solved

Vector vs Hashmap

Posted on 2004-08-27
38
5,912 Views
Last Modified: 2013-12-14
I know Hashmap or Hashtable are faster than List or normal Array

But when I have tested this program, I get the results showing the results in anotherway

Is this because of creating key as object and getting value in printM method??



import java.util.*;

public class  CollectionTest
{
      public Vector v=new Vector();
      public HashMap map=new HashMap();
      Date start=new Date();
      Date end=new Date();
      public static void main(String[] args)
      {
            System.out.println("Hello World!");
            CollectionTest test=new CollectionTest();
            System.err.println("Vector Test");
            test.addV();
            test.printV();

            System.err.println("Map Test");
            test=new CollectionTest();
            test.addM();
            test.printM();


      }
      public void addV()
      {
            start=new Date();
            for(int i=0;i<100000;i++)
            {
                  v.add(new Integer(i));
            }
      }
      public void printV()
      {
            
            for(int i=0;i<v.size();i++)
            {
                  Object k=v.get(i);
            }
            end=new Date();
            System.err.println("Total Time :"+(end.getTime()-start.getTime()));
      }
      public void addM()
      {
            start=new Date();
            for(int i=0;i<100000;i++)
            {
                  Integer ii=new Integer(i);
                  map.put(ii,ii);
            }
      }
      public void printM()
      {
            
            for(int i=0;i<map.size();i++)
            {
                  Object k=map.get(new Integer(i));
            }
            end=new Date();
            System.err.println("Total Time :"+(end.getTime()-start.getTime()));
      }

}
0
Comment
Question by:sudhakar_koundinya
  • 13
  • 9
  • 8
  • +3
38 Comments
 
LVL 35

Expert Comment

by:TimYates
ID: 11911284
No, Hashmap has no order

it's like a bag full of stuff, you can reach in, and grab one of the objects, but which order you get them out is not defined...
0
 
LVL 35

Accepted Solution

by:
TimYates earned 45 total points
ID: 11911312
>  I know Hashmap or Hashtable are faster than List or normal Array

Ahhh..I see what you mean...

Hashmaps and Hashtables are faster than lists for finding a specific object...

Ie;  go through your list and try to find "new Integer( 50000 )"

for the list, you would start at 0, and have to do 50000 searches to find it...

Hashmap would return it much quicker...

What you are doing here is using Hashmap for a purpose it was not designed for
0
 
LVL 6

Assisted Solution

by:expertmb
expertmb earned 45 total points
ID: 11911356
accessing an object using index is faster.
0
Netscaler Common Configuration How To guides

If you use NetScaler you will want to see these guides. The NetScaler How To Guides show administrators how to get NetScaler up and configured by providing instructions for common scenarios and some not so common ones.

 
LVL 14

Author Comment

by:sudhakar_koundinya
ID: 11911369
>>What you are doing here is using Hashmap for a purpose it was not designed for

I am checking all design constraints for my project.

>>go through your list and try to find "new Integer( 50000 )

Wait, wait Just tested again


import java.util.*;

public class  CollectionTest
{
      public Vector v=new Vector();
      public HashMap map=new HashMap();
      Date start=new Date();
      Date end=new Date();
      public static void main(String[] args)
      {
            System.out.println("Hello World!");
            CollectionTest test=new CollectionTest();
            System.err.println("Vector Test");
            test.addV();
            test.printV(10009);

            System.err.println("Map Test");
            test=new CollectionTest();
            test.addM();
            test.printM(10009);


      }
      public void addV()
      {
            start=new Date();
            for(int i=0;i<100000;i++)
            {
                  v.add(new Integer(i));
            }
      }
      public void printV(int i)
      {
            //start=new Date();
//            for(int i=0;i<v.size();i++)
            {
                  Object k=v.get(i);
            }
            end=new Date();
            System.err.println("Total Time :"+(end.getTime()-start.getTime()));
      }
      public void addM()
      {
            start=new Date();
            for(int i=0;i<100000;i++)
            {
                  Integer ii=new Integer(i);
                  map.put(ii,ii);

            }
      }
      public void printM(int i)
      {
            //start=new Date();
      //      for(int i=0;i<map.size();i++)
            {
                  Object k=map.get(new Integer(i));
            }
            end=new Date();
            System.err.println("Total Time :"+(end.getTime()-start.getTime()));
      }

}


The results are because of addiing the objects to Map.

Will it be slower for map while adding the objects??

0
 
LVL 35

Expert Comment

by:TimYates
ID: 11911394
> Will it be slower for map while adding the objects??

Yes, but MUCH faster finding them again...
0
 
LVL 6

Expert Comment

by:expertmb
ID: 11911410
sudhakar,
are you trying to access an object or want particular object in collection.
searching an element using key is much faster than going thru entire list and
comparing particular object.
0
 
LVL 14

Author Comment

by:sudhakar_koundinya
ID: 11911412
So for dynamic addition of objects then which do you prefer??

0
 
LVL 35

Expert Comment

by:TimYates
ID: 11911416
But slower at iterating over the whole collection...
0
 
LVL 24

Assisted Solution

by:sciuriware
sciuriware earned 20 total points
ID: 11911419
The hashing system is as old as the mainframe.
The idea is to oversize the container so that you can just drop objects in their estimated place without order.
The place is calculated from the so called hashing algorithm and should be chosen with care.
If you don't pre-allocate and oversize the map all goodies will go.

When I teach I give this example: pick up all cards of one colour, say Spades; that's 13 cards.
See if those can be placed on the table side by side.
Now, shuffle them and place them one by one in their position (Ace left, King Right).
As you can see you can store AND retrieve in ONE move, because there's plenty of space.
Now start over with 13 random cards from the deck; try the same trick, but put a card
to the right of an already occupied place (again 13 different numbers would be rare).
Now you can store AND retrieve in ALMOST one move, but not always.
Restart all over but make sure there's room for 26 cards (13 x 2). See what happens.

To do the same with the names of all people in some area will fail if you just use their name as a key.
Too many names start with the same sequence.
So, you must find an algorithm that spreads them evenly over the "table" again.

;JOOP!
0
 
LVL 35

Expert Comment

by:TimYates
ID: 11911421
>  So for dynamic addition of objects then which do you prefer??

It depends what you intend to do with the collection...

Do you want it sorted?  Are you going to be iterating over the whole list?  Are you going to be adding duplicates?
0
 
LVL 24

Expert Comment

by:sciuriware
ID: 11911425
All the other comments came in while I was typing..........
;JOOP!
0
 
LVL 14

Author Comment

by:sudhakar_koundinya
ID: 11911426
no just adding and accessing
0
 
LVL 14

Author Comment

by:sudhakar_koundinya
ID: 11911433
>>Do you want it sorted?  Are you going to be iterating over the whole list?  Are you going to be adding duplicates?

No sorting just traverse the entire List. No duplicates
0
 
LVL 35

Expert Comment

by:TimYates
ID: 11911434
> and accessing

individual items?

Then I'd use a HashMap
0
 
LVL 35

Expert Comment

by:TimYates
ID: 11911438
> No sorting just traverse the entire List. No duplicates

Ahhh...

ArrayList then...
0
 
LVL 35

Assisted Solution

by:girionis
girionis earned 20 total points
ID: 11911442
> no just adding and accessing

Yes it will be faster than a vector or arraylist.
0
 
LVL 35

Expert Comment

by:TimYates
ID: 11911446
I'm confused now ;-)
0
 
LVL 35

Expert Comment

by:girionis
ID: 11911447
> No sorting just traverse the entire List. No duplicates

Use a vector then.
0
 
LVL 14

Author Comment

by:sudhakar_koundinya
ID: 11911449
>>ArrayList then...

Doing the same now, using Vector. Searching for better Idea
0
 
LVL 35

Expert Comment

by:TimYates
ID: 11911452
> No sorting just traverse the entire List. No duplicates

If this is true, use an ArrayList

>  no just adding and accessing

If this is true, use a HashMap
0
 
LVL 6

Expert Comment

by:expertmb
ID: 11911454
>>So for dynamic addition of objects then which do you prefer??
>>no just adding and accessing

If objects are not thread safe then go ArrayList
if want thread safe go with Vector.
if want search and then access object go with HashMap.
0
 
LVL 35

Expert Comment

by:TimYates
ID: 11911455
> Doing the same now, using Vector. Searching for better Idea

ArrayList is faster than Vector ;-)
0
 
LVL 35

Expert Comment

by:girionis
ID: 11911457
Bah.. too many comments at once :)

Well for just adding and retrieving I'd use a map. For adding, sorting and retrieving I'd use a collection.
0
 
LVL 6

Expert Comment

by:expertmb
ID: 11911460
>>accessing an object using index is faster.
0
 
LVL 35

Expert Comment

by:TimYates
ID: 11911465
From: http://java.sun.com/docs/books/tutorial/collections/implementations/general.html

----------

Most of the time, you'll probably use ArrayList. It offers constant time positional access, and it's just plain fast, because it does not have to allocate a node object for each element in the List, and it can take advantage of the native method System.arraycopy when it has to move multiple elements at once. Think of ArrayList as Vector without the synchronization overhead.
0
 
LVL 14

Author Comment

by:sudhakar_koundinya
ID: 11911471

>>> No sorting just traverse the entire List. No duplicates

>>If this is true, use an ArrayList

>>>  no just adding and accessing

>>If this is true, use a HashMap

I am confused :-(
0
 
LVL 14

Author Comment

by:sudhakar_koundinya
ID: 11911482

>>If this is true, use a HashMap

But dynamic addition is becoming slow know??
0
 
LVL 35

Expert Comment

by:TimYates
ID: 11911505
> But dynamic addition is becoming slow know??

It takes 464 milliseconds to add the 100000 items in your first example to the HashMap...  

Not really a performance hit...  I'd imagine memory is an issue before time is...
0
 
LVL 35

Expert Comment

by:TimYates
ID: 11911508
> It takes 464 milliseconds to add the 100000 items in your first example to the HashMap...  

Errr...that's to iterate the map...hang on...

No, that's to add them all in, AND get them all out...
0
 
LVL 35

Expert Comment

by:girionis
ID: 11911555
Even if adding all the objects in a map is a bit slower than adding them to a collection, retrieving them from a map will by far outperform retrieving them from a collection.
0
 
LVL 6

Expert Comment

by:expertmb
ID: 11911558
sudha,
when you add object to the vector if you look at src of vector in jdk it just adds obejct to an object array.
when you add(put) an object in map it does more things like hashing, indexFor etc...

its as simpe as, more the statement to execute more the time it takes.

mb...
0
 
LVL 6

Expert Comment

by:expertmb
ID: 11911580
>>more the statement to execute more the time it takes.
add() of vector has less statements to execute before it adds toits internal object  array than the put() of Map.
0
 
LVL 6

Expert Comment

by:expertmb
ID: 11911630
similarly get() of vector just checks the internal object array size and returns element at particular index from the array. incase of map it executes more statements then finally returns the particular object.
0
 
LVL 6

Expert Comment

by:expertmb
ID: 11911649
in Vector and ArrayList you can add duplicate elements.
0
 
LVL 6

Expert Comment

by:expertmb
ID: 11911665
if you dont want have duplicate elements in your collection then you can use any implementation of Set.
0
 
LVL 18

Assisted Solution

by:armoghan
armoghan earned 20 total points
ID: 11911891
Ahhh
So many comments.
As far as I remember about the difference from my Algorithm class way back.

Hashing is always faster in retreving the items, as they bring the result in O(1)

Arrays used to be good in sorting, moving around the things but takes time in searching.

Hashing may be slower in addition

So I usually use arraylist when I have to use a limited number of values to search /add/delete/
and If a fast search is required and number of items are much more.. Then I usually go for hashing

I dont remember any more :) Rest could be in a good Algoritm book :)
0
 
LVL 14

Author Comment

by:sudhakar_koundinya
ID: 11915459
Ok I decided to stick with Vector only as it is multithreaded environment.

In my case not only fetching but adding is  also important.

Thanks
Sudhakar

0
 
LVL 35

Expert Comment

by:girionis
ID: 11915496
:)
0

Featured Post

VMware Disaster Recovery and Data Protection

In this expert guide, you’ll learn about the components of a Modern Data Center. You will use cases for the value-added capabilities of Veeam®, including combining backup and replication for VMware disaster recovery and using replication for data center migration.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
windows explorer path to command prompt 5 45
Unhandled exception type Exception 18 31
Java Restore security prompts not working 10 13
Java: anonymous class 4 22
Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
How to install Selenium IDE and loops for quick automated testing. Get Selenium IDE from http://seleniumhq.org Go to that link and select download selenium in the right hand columnThat will then direct you to their download page.From that page s…
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.
The viewer will learn how to use NetBeans IDE 8.0 for Windows to connect to a MySQL database. Open Services Panel: Create a new connection using New Connection Wizard: Create a test database called eetutorial: Create a new test tabel called ee…

803 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question