hello !

its stupid to ask this question......but has anyone implemented hash maps in java ?

can someone please post a code here. im really unable to implement it and unless i dont do that, it'll be very difficult to understand its concept.

thank you.

yes....implementation of hash maps.

i mean.....implementing the concept of key and values.

Ok, here are a couple of trivial examples.

// phone list
Map<String,String> phoneNumbers = new HashMap<String,String>();

phoneNumbers.put("Bob","234-3456");
phoneNumbers.put("Mary","444-5555");
phoneNumbers.put("Tom","777-9900");

System.out.println("Bob's phone number is: "+phoneNumbers.get("Bob"));
System.out.println();
System.out.println("All phone entries");
System.out.println("-----------------");
for (Map.Entry<String,String> entry : phoneNumbers.entrySet()){
    System.out.println(entry.getKey()+": "+entry.getValue());
}

// counting the number of times a letter appears in text
System.out.println();
String text = "'If trees could scream, would we be so cavalier about cutting them down? We might, if they screamed all the time, for no good reason.' - Jack Handy";
Map<Character,Integer> letterCounts = new TreeMap<Character,Integer>();
for (char c : text.toCharArray()){
    if (Character.isLetter(c)){
        Integer count = letterCounts.get(Character.toLowerCase(c));
        letterCounts.put(Character.toLowerCase(c), 
          count==null ? 1 : count+1);
    }
}

System.out.println(text);
System.out.println("");
System.out.println("Letter occurences:");
System.out.println("-------------------");
for (Map.Entry<Character,Integer> entry : letterCounts.entrySet()){
    System.out.println(entry.getKey()+": "+entry.getValue());
}
This article has been dead for over six months. Start a new discussion instead.