溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Java的注意事項有什么

發(fā)布時間:2021-10-21 13:52:39 來源:億速云 閱讀:112 作者:柒染 欄目:大數(shù)據(jù)

本篇文章為大家展示了Java的注意事項有什么,內容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細介紹希望你能有所收獲。

1、 不要在 foreach 循環(huán)里進行元素的 remove/add 操作,可以在fori中進行remove/add。remove 元素請使用 Iterator 方式,如果并發(fā)操作,需要對 Iterator 對象加鎖。【參考:https://my.oschina.net/u/3955185/blog/4496726】

//正例一:
List<String> list = new ArrayList<>();
list.add("1");
list.add("2");
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
    String item = iterator.next();
    if (刪除元素的條件) {
        iterator.remove();
    }
}
//正例二:
for (int i=0;i < list.size();i++) {
    if (list.get(i)==2) {
        list.remove(i);
    }
}

//反例:
for (String item : list) {
    if ("2".equals(item)) {
        list.remove(item);
    }
}

原因:由于foreach底層是用iterator進行遍歷,源代碼如下:

public E next() {
            checkForComodification();
            int i = cursor;
            if (i >= size)
                throw new NoSuchElementException();
            Object[] elementData = ArrayList.this.elementData;
            if (i >= elementData.length)
                throw new ConcurrentModificationException();
            cursor = i + 1;
            return (E) elementData[lastRet = i];
        }

其中checkForComodification()具體實現(xiàn)為:

final void checkForComodification() {
    if (modCount != expectedModCount){
        throw new ConcurrentModificationException();
    }
}

從源代碼可以看出,當modCount != expectedModCount 會拋異常,使用list的remove()操作之后,modCount會加1,但是expectedModCount不會加1,即兩值不等,會拋異常。 使用Iterator的remove()會更改expectedModCount的值,故需使用此方式進行remove/add。

public void remove() {
    if (lastRet < 0){
        throw new IllegalStateException();
    }
    
    checkForComodification();

    try {
        ArrayList.this.remove(lastRet);
        cursor = lastRet;
        lastRet = -1;
        expectedModCount = modCount;
    } catch (IndexOutOfBoundsException ex) {
        throw new ConcurrentModificationException();
    }
}

如果使用fori進行remove/add,不會走checkForComodification()方法,所以也可以使用fori進行操作,如正例2。

2、Integer比較的時候,使用equals,否則當比較的數(shù)據(jù)不在-128-127之間,比較的不是值,而是對象的引用,比較結果不是預期值。

上述內容就是Java的注意事項有什么,你們學到知識或技能了嗎?如果還想學到更多技能或者豐富自己的知識儲備,歡迎關注億速云行業(yè)資訊頻道。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內容。

AI