同样的实现不一样的写法.....我困惑了
import java.util.*;
class TreeMapTest
{
public static void main(String[] args)
{
String s = "aafsdl,gdslkj/ssjf";
charCount(s);
}
public static String charCount(String str)
{
char[] chs = str.toCharArray();
int count = 0;
TreeMap<Character,Integer> tm = new TreeMap<Character,Integer>();
for (int x=0;x<chs.length; x++)
{ //字符串中可能出现其他字符,所以这里我们要判断一下
if(chs[x]>='a'&&chs[x]<='z'||chs[x]>='A'&&chs[x]<='Z')
{ /*
Integer Value = tm.get(chs[x]);
if(!(Value==null))//if(Value!==null)这两句我觉得是相同的意思,但是却有着不一样的效果? count = Value;
count++;
tm.put(chs[x],count);
*/
Integer Value = tm.get(chs[x]);
if(Value == null)
tm.put(chs[x],1);
else
{
Value+=1;
tm.put(chs[x],Value);
}
}
//else不加这个运行也正常,加else有什么意义? //continue;
}
//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 in = me.getValue();
System.out.print(ch.toString()+"("+in.toString()+")");
}
return null;
}
}
高手帮我分析下我这样写的弊端:( |