设为首页 加入收藏

TOP

不良代码展示-两个数组找不同
2014-11-23 23:36:35 来源: 作者: 【 】 浏览:4
Tags:不良 代码 展示 两个数 不同

不良代码:

public class WrongCompare {

/**

* @param args the command line arguments

*/

public static void main(String[] args) {

String[] str1 = {"1","2","3","4","5","6",};

String[] str2 = {"0","2","3","4","5","6","7",};

for(int i = 0; i < str1.length; i++) {

boolean has = false;

for(int j = 0; j < str2.length; j++) {

if (str1[i].equals(str2[j])) {

has = true;

break;

}

}

if (!has) {

System.out.println(str1[i] + " 在str1中,不在str2中");

}

}

for(int j = 0; j < str2.length; j++) {

boolean has = false;

for(int i = 0; i < str1.length; i++) {

if (str1[i].equals(str2[j])) {

has = true;

break;

}

}

if (!has) {

System.out.println(str2[j] + " 在str2中,不在str1中");

}

}

}

}

比较两个数组的不同,竟然用了2次双层循环去做判断。这个开销是很大的。

有时候,我们会发现自己写的程序,调试的时候没什么问题,一旦在真实环境下就慢的受不了。

平时写代码的时候,就要注意技巧。

可以用的方法:

public class RightCompare {

/**

* @param args the command line arguments

*/

public static void main(String[] args) {

String[] str1 = {"1","2","3","4","5","6",};

String[] str2 = {"0","2","3","4","5","6","7",};

Set set1 = new HashSet();

Set set2 = new HashSet();

set1.addAll(Arrays.asList(str1));

set2.addAll(Arrays.asList(str2));

Iterator iter = set1.iterator();

while(iter.hasNext()) {

Object o = iter.next();

if (set2.contains(o)) {

set2.remove(o);

} else {

System.out.println(o + " 在str1中,不在str2中");

}

}

iter = set2.iterator();

while(iter.hasNext()) {

Object o = iter.next();

System.out.println(o + " 在str2中,不在str1中");

}

}

}

用Set的方法。set不是用列表方式去存放数据,无序的存放,在效率上会更高一些。

Hashset用的是哈希散列算法去存放数据,判断数据是否在集合内,开销比列表里的判断要快不少,特别是大数据集的时候。

在手机开发的时候,这种效率上的提升,会更明显。

摘自:http://blog.cs dn.net/yihui823/article/details/6912428

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇c语言:计算输入字符个数及字母出.. 下一篇不用第三方变量如何交换两个整形数

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: