当前位置: 代码迷 >> J2SE >> 代码中有疑惑之处请解释一下
  详细解决方案

代码中有疑惑之处请解释一下

热度:128   发布时间:2016-04-23 20:16:24.0
代码中有不解之处请解释一下

*/
import java.util.*;
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>();


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;
/*
if(value==null)
{
tm.put(chs[x],1);
}
else
{
value = value + 1;
tm.put(chs[x],value);
}
*/


}

//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();
}

}

疑问:在红色代码前,字符串已经处理为tm集合了(那个循环体的作用就是),又如何突然又能放到StringBuilder里呢?我这里无法理解。
------解决思路----------------------
函数要返回的是string,tm是一个treemap,当然要用stringbuilder
------解决思路----------------------
new的时候是空的,append才有东西