Hash Map

  • Arrays & Lists stores elements as ordered collections, with each element given an integer index.
  • HashMap is used for storing data collection as key and value pairs.One object is used as key(index) to another object(the value).
  • To put , remove & get methods are used to add delete and access values in the HashMap.
  • Example-
    import java.util.HashMap;
    public class Myclass{
           public static void main(String args[]){
               HashMap<String,Integer> points = new HashMap<String,Integer>();
               points.put("Bob",154);
               points.put("Dave",167);
               points.put("Rob",754);
               System.out.println(points.get("Dave"))
       }
    }
    Output-
    42
  • we have created a HashMap with String as its Key & Integer as it values.
  • Use the get method & the corresponding key to access the HashMap Element.
  • A HashMap cannot contains duplicate keys.Adding a new item with a key that already exists overwrites the old elements.
  • The HashMap class provides containKey and containValue method that determine the presence of a specified key or value.
  • If you try to get a value that is not present in your map ,it returns the value of null.
  • null is special type that represents the absence of a value.

Sets

  • A set is a collection that contains duplicate elements. It models the mathematical set abstraction.
  • One of the implementation of the set is the HashSet class.
  • Example-
    import java.util.HashSet;
    public class Myclass{
          public static void main(String args[]){
                HashSet<String> set = new HashSet<String>();
                set.add("A");
                set.add("B");
                System.out.println(set);
        }
    }
    output-
    [A B]
  • You can use the size() method to get the number of elements in HashSet.Example- System.out.println(set.size());
  • What is hashing ?
  • A hash table stores information through a mechanism called hashing , in which a key’s informational content is used to determine a unique value called a hash code.
  • So basically each element in the HashSet is associated with its unique hash code.