在代码的编写中,我们只要稍微注意一下也许可以做到更好。下面是我的一些小小发现,敬请大家指正和补充:- //1.数据交换
- public static void swap(int[] num,i,j)
- {
- /*
- 习惯性写法
- int temp=num[i];
- num[i]=num[j];
- num[j]=temp;
- */
- //也许这么写也不错
- num[i]=num[i]^num[j];
- num[j]=num[i]^num[j];
- num[i]=num[i]^num[j];
- }
- //2.定义变量的位置
- public static void prints(int[] num)
- {
- /*
- int i=0;
- for(;i<num.length;i++)
- {
- System.out.println(num[i])
- }
- */
- //显然,上面的写法就不让下面的写法合理
- for(int i=0;i<num.length;i++)
- {
- System.out.println(tm)
- }
- }
- /*
- 定义局部变量的时候尽量保证使用完成能够最快的被垃圾回收器回收,
- 当然,上面的例子太easy,可能大家没什么感觉。如果毕老师的视频看到16天的同学可以看一下老师写的一段代码
- 现在我们给它小小的优化一下
- */
- public static String charCount(String str)//
- {
- char[] chs = str.toCharArray();
- TreeMap<Character,Integer> tm = new TreeMap<Character,Integer>();
-
- int count = 0;//count 作为计数器,
- 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;
- /* count 的出现就是为了优化以下代码存在的
- if(value==null)
- {
- tm.put(chs[x],1);
- }
- else
- {
- value = value + 1;
- tm.put(chs[x],value);
- }
- */
- }
- /*下面我们看一下for循环的优化
- for(int x=0,count=0; x<chs.length; x++,count=0)
- {
- //循环主体不变,count=0可以去掉了。
- //这样既可以避免了在主体中定义变量造成的循环过程中反复开辟空间,又能尽可能的保证循环结束,count被垃圾回收。
-
- }
- */
复制代码
|
|