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.

原文地址:https://www.cnblogs.com/yanyuechao/p/8371192.html