Are you still using Java1.4 or earlier? If not, please go find out about the complicated subject of
Generics. That will produce compiler errors that you are using the wrong types, rather than runtime Exceptions. Your code, unchanged, can be compiled like this, in which case it produces about 8 warnings:
javac -Xlint CompClass.java
There are 3 classes which should be parameterised:
empMap should be declared as Map<Integer, String> and instantiated as new TreeMap<Integer, String>.empNameMap which you are using as Map<Integer, String> and should be instantiated as TreeMap<Integer, String>.EmpNameComparator which should be declared as implementing Comparable<EmpClass> and the compare method would take EmpClass as type for both its parameter.You might be able to declare both Maps as SortedMap or NavigableMap with the same <> instead.
You are passing Integer, String to both Maps, but if you look in the
API for TreeMap you find that the Comparator operates on the left-hand parameter in put, the Key. So the Comparator is actually operating on Integers not EmpClasses. In fact you don't appear to use any EmpClass objects in your main method at all. The Comparator is actually redundant; you are using the same procedure as in the first Map. What happens there is that the Map can use any Object which implements the Comparable<T> interface as a Key; Integer implements Comparable<Integer> so it will work nicely. It is only when it finds a Comparator requiring EmpClasses and you present it with a second Integer that it has problems. It only has problems when the second pair is "put" in the Map because it never tries to compare the first with anything!
By the way: You can shorten your equals method to
You ought also to override the hashCode() method to take empNo into account. It seems strange that you are not using empName in the equals() method. Using instanceof in an equals method can produce wrong results if presented with a subclass of EmpClass.