for循環里面不要進行remove操作,for循環里remove元素后,list的下標會減小,導致遍歷不完全


1,不要在 foreach 循環里進行元素的 remove/add 操作


remove 元素請使用 Iterator方式,如果並發操作,需要對 Iterator 對象加鎖。

正例:

Iterator<String> iterator = list.iterator(); 
while (iterator.hasNext()) { String item = iterator.next();
if (刪除元素的條件) { iterator.remove(); } }

反例:

public static void main(String args[]){
        List<String> list = new ArrayList<String>();
        list.add("1");
        list.add("1");
        for (String item : list) {
            if ("1".equals(item)) { list.remove(item);
        } }
        System.out.println(list.toString());
    }
//output: [1]

for循環里remove元素后,list的下標會減小,導致遍歷不完全。

 

2,asList 的返回對象是一個 Arrays 內部類,並沒有實現集合的修改方法。

Arrays.asList 體現的是適配器模式,只是轉換接口,后台的數據仍是數組。

String[] str = new String[] { "you", "wu" };
List list = Arrays.asList(str);
str[0] = "yy";
System.out.println(list.toString());
//output: [yy, wu]
list.add("yangguanbao"); 
//運行時異常

3,集合類型轉換為數組, 要防止數組下標越界的問題。用以下方式轉化

List<String> list = new ArrayList<String>(2); 
list.add("guan");
list.add("bao");
String[] array = new String[list.size()];  

 

4, try{} catch{}語句塊

finally的代碼塊一定會被執行,即使finally代碼塊之前函數有return語句,finally代碼塊也會執行

除以下一種特例: System.exit(0);這條語句后的finally將不再執行

finally的作用是無論是否有異常發生,都要對資源進行釋放;資源釋放在finally里面

5,同一個類的每個對象有不同成員變量存儲空間

 

同一個類的每個對象共享方法

6,java比較對象時,“==”比較的是對象在內存堆內的地址

 

String重寫了Object的equals方法,因而兩個相同的字符串,equal返回是true:

public boolean equals(Object anObject)

Compares this string to the specified object.

The result is true if and only if the argument is not null and is a String object

that represents the same sequence of characters as this object.

 

5,B.isinstance(A) 判斷

Determines if the specified {@code Object} is assignment-compatible
with the object represented by this {@code Class}. This method is
the dynamic equivalent of the Java language {@code instanceof}
operator. The method returns {@code true} if the specified
{@code Object} argument is non-null and can be cast to the
reference type represented by this {@code Class} object without
raising a {@code ClassCastException.} It returns {@code false}
otherwise.
確定B類是否兼容調用A類,B.isinstance(A)動態相等於A.class instanceof B.class,
如果A不是空並且A類型可以被強轉成B類型,那么返回true,
否則返回false.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM