Sunday 13 April 2014

get : Get the Value from key

V get(Object key)
return the value to which the specified key is mapped, or null if this map contains no mapping for the key.

import java.util.*;

class MapGetValue{
  public static void main(String args[]){
    Map<Integer, String> mapEx = new TreeMap<> ();
  
  /* Add Data to mapEx */
  mapEx.put(1, "HI");
  mapEx.put(2, "How");
  mapEx.put(3, "Are");
  
 System.out.println("Key 1 has value " +mapEx.get(1));
 System.out.println("Key 2 has value " +mapEx.get(2));
 System.out.println("Key 3 has value " +mapEx.get(3));
  }
}

Output
Key 1 has value HI
Key 2 has value How
Key 3 has value Are

1. Return null if this map contains no mapping for the key
import java.util.*;

class MapGetNull{
  public static void main(String args[]){
    Map<Integer, String> mapEx = new TreeMap<> ();
  
  /* Add Data to mapEx */
  mapEx.put(1, "HI");
  mapEx.put(2, "How");
  mapEx.put(3, "Are");
  
 System.out.println("Key 4 has value " +mapEx.get(4));
  }
}

Output
Key 4 has value null

2. throws ClassCastException if the key is of an inappropriate type for
this map
class Student{
  String firstName, lastName;
 
  Student(String firstName, String lastName){
    this.firstName = firstName;
  this.lastName  = lastName;
  }
}

import java.util.*;

class MapGetClassCast{
  public static void main(String args[]){
    Map<Integer, Student> mapEx = new TreeMap<> ();
  
  Student s1 = new Student("abcd", "defg");
  mapEx.get(s1);
  }
}

Output
Exception in thread "main" java.lang.ClassCastException: Student cannot be cast
to java.lang.Comparable
        at java.util.TreeMap.getEntry(TreeMap.java:343)
        at java.util.TreeMap.get(TreeMap.java:273)
        at MapGetClassCast.main(MapGetClassCast.java:8)

3. throws NullPointerException if the specified key is null and this map does not permit null keys
import java.util.*;

class MapGetNullPointer{
  public static void main(String args[]){
    Map<Integer, String> mapEx = new TreeMap<> ();
    mapEx.get(null);
  }
}

Output
Exception in thread "main" java.lang.NullPointerException
        at java.util.TreeMap.getEntry(TreeMap.java:342)
        at java.util.TreeMap.get(TreeMap.java:273)
        at MapGetNullPointer.main(MapGetNullPointer.java:6)



Prevoius                                                 Next                                                 Home

No comments:

Post a Comment