java 中TreeMap的一个错误,麻烦大哥们给检查下!

2025-01-07 02:02:01
推荐回答(2个)
回答1:

import java.util.*;

public class TreeMapTest
{
public static void main(String[] args)
{
TreeMap map = new TreeMap(new MyComparator());

/*错误在此行,提示:Exception in thread "main" java.lang.Error: Unresolved compilation problems:
Syntax error on token "new", delete this token
MyComparator cannot be resolved to a variable

at com.yang2.TreeMapTest.main(TreeMapTest.java:13)*/

map.put("a","aaa");
map.put("b","bbb");
Set set = map.entrySet();
for(Iterator iter = set.iterator(); iter.hasNext(); )
{
Map.Entry entry = (Map.Entry)iter.next();
String key = (String)entry.getKey();
String value = (String)entry.getValue();

System.out.println(key + ":" + value);
}

}
}
class MyComparator implements Comparator
{
public int compare(Object obj1,Object obj2)
{
String str1 = (String)obj1;
String str2 = (String)obj2;

return str1.compareTo(str2);
}
}
entrySet() : 返回此映射中包含的映射关系的 Set 视图。

回答2:

import java.util.Comparator;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;

public class TreeMapTest
{
public static void main(String[] args)
{
TreeMap map = new TreeMap(new MyComparator());
map.put("a","aaa");
map.put("b","bbb");

for( Iterator it = map.entrySet().iterator(); it.hasNext(); )
{
Map.Entry entry = (Map.Entry)it.next();
String key = (String)entry.getKey();
String value = (String)entry.getValue();

System.out.println(key + ":" + value);
}

}
}
class MyComparator implements Comparator
{
public int compare(Object obj1,Object obj2)
{
String str1 = (String)obj1;
String str2 = (String)obj2;

return str1.compareTo(str2);
}
}

/*
从错误信息可以看出是 new MyComparator 的后面没有括号是原因
还有就是for的地方有点问题我给你改了一下

*/