Sunday, 13 April 2014

containsKey : Search for a Key in the Map

boolean containsKey(Object key)
Returns true if this map contains a mapping for the specified key.

import java.util.*;
class MapContains{
  public static void main(String args[]){
    Map<Integer, String> studentTable = new TreeMap<> ();
  
  /* Add Student details to studentTable */
  studentTable.put(123, "Krishna");
  studentTable.put(124, "Ram");
  studentTable.put(125, "Anil");
  studentTable.put(126, "Kiran");
  
  System.out.println("\nData in studentTable is");
  System.out.println(studentTable);

  System.out.print("Is studentTable contains 123 ");
  System.out.println(studentTable.containsKey(123));
  
  System.out.print("Is studentTable contains 1 ");
  System.out.println(studentTable.containsKey(1));
  }
}

Output
Data in studentTable is
{123=Krishna, 124=Ram, 125=Anil, 126=Kiran}
Is studentTable contains 123 true
Is studentTable contains 1 false

1. 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 MapContainsClassCast{
  public static void main(String args[]){
    Map<Student, Integer> studentTable = new TreeMap<> ();
  
  /*Create Student Objects */
  Student s1 = new Student("Praneeth", "Sai");
  studentTable.containsKey(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.containsKey(TreeMap.java:227)
        at MapContainsClassCast.main(MapContainsClassCast.java:8)

To make the program runs fine, Student class must implements the Comparable interface like below.

class Student implements Comparable{
  String firstName, lastName;
 
  Student(String firstName, String lastName){
    this.firstName = firstName;
  this.lastName  = lastName;
  }
  
  public int compareTo(Object s){
  if(s==null)
  return -1;
  Student std = (Student) s;
  return firstName.compareTo(std.firstName);
  }
}

2. throws NullPointerException if the specified key is null and this map
does not permit null keys
import java.util.*;
class MapContainsNull{
  public static void main(String args[]){
    Map<String, Integer> studentTable = new TreeMap<> ();

  studentTable.containsKey(null);
  }
}

Output
Exception in thread "main" java.lang.NullPointerException
        at java.util.TreeMap.getEntry(TreeMap.java:342)
        at java.util.TreeMap.containsKey(TreeMap.java:227)
        at MapContainsNull.main(MapContainsNull.java:6)







Prevoius                                                 Next                                                 Home

No comments:

Post a Comment