本篇文章為大家展示了Java的注意事項有什么,內容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細介紹希望你能有所收獲。
1、 不要在 foreach 循環里進行元素的 remove/add 操作,可以在fori中進行remove/add。remove 元素請使用 Iterator 方式,如果并發操作,需要對 Iterator 對象加鎖?!緟⒖迹篽ttps://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()具體實現為:
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,否則當比較的數據不在-128-127之間,比較的不是值,而是對象的引用,比較結果不是預期值。
上述內容就是Java的注意事項有什么,你們學到知識或技能了嗎?如果還想學到更多技能或者豐富自己的知識儲備,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。