I have a code that creates TreeMap
and fill it then try to sort it by integers values available in it. But it gives me a red line under the TreeMap
[showing the compiler error "reference to TreeMap is ambiguous"] and I do not know why. The following is my code:
package treemap;
import java.util.*;
import java.util.HashSet;
import java.util.TreeMap;
import java.util.Set;
import java.util.Iterator;
import java.util.Map;
public class TreeMap {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
try {
TreeMap<Integer, String> hm = new TreeMap<Integer, String>();
hm.put(100, "Amit");
hm.put(102, "Ravi");
hm.put(101, "Vijay");
hm.put(103, "Rahul");
for (Map.Entry m : hm.entrySet()) {
System.out.println(m.getKey() + " " + m.getValue());
}
} catch (Exception e) {
System.out.println(e);
}
}
}
Can you help me?
The problem is caused because your code refers to two different classes (your own TreeMap
class, and the JDK collection class TreeMap
) with the same handle, "TreeMap", and the compiler cannot know which is which. The easiest, and probably most elegant, way to fix the problem is to rename your class so that it's name is no longer the same as any of the other classes being referred to within it. As suggested by others, renaming your class to TreeMapTest
will fix your problem.
However, note that while renaming your class is probably the best solution, it is perfectly legal to give your class the same name as another class. But then you need to use a fully-qualified name when referring to the other class, so that the compiler knows when you're referring to your own class and when you're referring to the other class of the same name.
So another way to fix your code would have been to replace the first line of your main
method with this:
java.util.TreeMap<Integer, String> hm = new java.util.TreeMap<>();
Because you're using the fully-qualified name (package name then class name) for the JDK TreeMap
collection class, the compiler knows that you're referring to that and not to your own TreeMap
class. (And if you're referring to the other class like this, you must get rid of the import java.util.TreeMap
line, as it's no longer needed.)