12/19/10

HashMap simple usage and understanding

Map is an object that stores key/volume pairs. Given a key, you can find its value. Keys must be unique, but values may be duplicated.
The HashMap class uses a hash table to implementation of the map interface. This allows the execution time of basic operations, such as get() and put() to be constant.

An example is below:


Q. Find the numbers Divisible by an array of numbers ie div[] between a range ie from 1 to N?
Ans.  This can be solved using many ways, but we will be solving using HashMap which will help u understand the concept of HashMap in a better way..

NOTE:
For this u can use your command prompt, eclipse, netbeans or any IDE that supports JAVA. Using eclipse is much easier.


CODE :


1:  import java.util.HashMap; 

2:  public class Main { 

3:    public static int usingHashmap(int N,int div[]){ 

4:      int count=0; 

5:      HashMap<Integer, Integer> key=new HashMap<Integer, Integer>(); 

6:      for(int i=1;i<N;i++){ 

7:        key.put(i, i); 

8:      } 

9:      for(int i=0;i<div.length;i++){ 

10:        for(int k=1;k<N;k++){ 

11:        if(key.get(k)==null){ 

12:          key.put(k, -1); 

13:        } 

14:          if(key.get(k)%div[i]==0){ 

15:            count++; 

16:            key.remove(k); 

17:          } 

18:        } 

19:      } 

20:      System.out.println(count); 

21:      return count; 

22:    } 

23:    public static void main(String[] args) { 

24:      new Main().usingHashmap(50, new int[]{3,2}); 

25:    } 

26:  } 

SHARE THIS POST:

Related Posts:

  • RGB Color Chooser Applet Java Code A RGB Color Chooser shows three sliders that the user can manipulate to set the red, green, and blue, components of a color. A color box shows the selected color, and there are three labels that show the numerical values of… Read More
  • Karel -the Robot learns Java using Eclipse Tutorial Karel The Robot is a robot simulator that affords a gentle introduction to computer programming. Users write Karel programs and feed them to the simulator to watch them execute. By solving karel problems you will build you… Read More
  • Microsoft SQL Server 2008 connection using ODBC tutorial My previous post was on SQL Server installation . Now today I will be telling how to connect your database ie SQL Server using ODBC with Netbeans. After you installed SQL Server 2008 Express successfully, now its time to … Read More
  • Java Tutorial : Identifiers, Keywords and Types Identifiers : In Java programming language, an identifier is a name given to a variable, class or method. Identifiers start with a letter, underscore(_) or dollar sign ($). The following characters can be digits. Identifi… Read More
  • Merge Sort using Java with program code In computer science, merge sort or mergesort is a sorting algorithm for rearranging lists (or any such linear sequential data storage structure) into a specified order. It is a particularly good example of the divide and co… Read More