不良代碼展示-兩個數組找不同

來源:互聯網
上載者:User

原創文章,如有轉載,請註明出處: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用的是雜湊散列演算法去存放資料,判斷資料是否在集合內,開銷比列表裡的判斷要快不少,特別是大資料集的時候。

在手機開發的時候,這種效率上的提升,會更明顯。



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.