不良代码展示-两个数组找不同

原创文章,如有转载,请注明出处:http://blog.csdn.net/yihui823/article/details/6912428

不良代码:

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

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



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值