Connect with us

CORE JAVA

Map Interface In Java

map_interface

Before deep dive in to Map interface concept & its implimentation, lets try to put some basic & fundamental rule of Map interface in java.

Here are hierarchey of Map Interface & its child classes & interfaces. There are other classes & interface which is not mentioned in the hierarchy tree. You can explore more on oracle official website here

mapinterfacetree

Key Point About Map Interface

mapentry

HashMap put() Method & return value

HashMap is a direct implementation class of the Map. Lets try to understand the return value of put() method in HasMap class.

				
					package javadsa;

import java.util.HashMap;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        Map<Integer,String> hm=new HashMap();
        String apple = hm.put(1, "Apple");
        String banana = hm.put(2, "Banana");
        String avocado = hm.put(3, "Avocado");

        System.out.println(apple);
        System.out.println(banana);
        System.out.println(avocado);

    }
}

				
			
mapoutput1

As we can see in the above example, the return value of all three put method is null.  

 Lets try to replace an entry with the same key and see the output.

 

				
					package javadsa;

import java.util.HashMap;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        Map<Integer,String> hm=new HashMap();
        String apple = hm.put(1, "Apple");
        String banana = hm.put(2, "Banana");
        String avocado = hm.put(3, "Avocado");
        String replacedFruit = hm.put(3, "Mango");

        System.out.println(apple);
        System.out.println(banana);
        System.out.println(avocado);
        System.out.println(replacedFruit);

    }
}

				
			

As we can see in the above example, when we try to insert any new entry(key,value pair) , if key is already present , then new entry replaced the old value and return the  old value .

Here Avocado is replaced by Mango & return Avacado.

Click to comment

Leave a Reply

Your email address will not be published. Required fields are marked *

More in CORE JAVA