本帖最后由 李罡 于 2013-3-18 18:54 编辑
- import java.util.*;
- class CharComparator implements Comparator<Zimu>
- {
- public int compare(Zimu z1,Zimu z2)
- {
- return new Character(z1.getName()).compareTo(new Character(z2.getName()));
- }
- }
- class Zimu
- {
- private char z;
- Zimu(char z)
- {
- this.z=z;
- }
- public char getName()
- {
- return z;
- }
- }
- class MapTest3
- {
- public static void main(String[] args)
- {
- String s= charCount("ak+abAf1c,dCkaAbc-defa");
- System.out.println(s);
- }
- public static String charCount(String str)
- {
- char[] chs = str.toCharArray();
- TreeMap<Character,Integer> tm = new TreeMap<Character,Integer>(new CharComparator());//为什么这里加个比较器就不行了
- int count = 0;
- for(int x=0; x<chs.length; x++)
- {
- if(!(chs[x]>='a' && chs[x]<='z' || chs[x]>='A' && chs[x]<='Z'))
- continue;
- Integer value = tm.get(chs[x]);
- if(value!=null)
- count = value;
- count++;
- tm.put(chs[x],count);//
- count = 0;
- }
- //System.out.println(tm);
- StringBuilder sb = new StringBuilder();
- Set<Map.Entry<Character,Integer>> entrySet = tm.entrySet();
- Iterator<Map.Entry<Character,Integer>> it = entrySet.iterator();
- while(it.hasNext())
- {
- Map.Entry<Character,Integer> me = it.next();
- Character ch = me.getKey();
- Integer value = me.getValue();
- sb.append(ch+"("+value+")");
- }
- return sb.toString();
- }
- }
- 加了比较器以后,显示:
- 错误: 对于TreeMap(CharComparator), 找不到合适的构造器
- TreeMap<Character,Integer> tm = new TreeMap<Character,Integer>(n
- ew CharComparator());
- 老师写的代码中是没有加比较器的,运行没问题的。可为什么我加了比较器以后编译就无法通过
- 了呢?比较器该怎么加呢?
- 另外可以说说hashset和treeset,compare和compareTo的区别吗
复制代码 |