1、集合转数组
集合转数组建议采用以下写法:
//接口方法
<T> T[] toArray(T[] a);
List<String> strList = new ArrayList<>();
strList.add("str1");
strList.add("str2");
strList.add("str3");
String[] strArray = strList.toArray(new String[strList.size()]);
而不要采用:
//接口方法
Object[] toArray();
String[] strArray = (String[]) strList.toArray();
这样不仅需要强转,而且会抛出以下异常:
java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;
2、删除集合中的元素一定要从角标大的往角标小的删
正确的删除顺序,大角标到小角标:
List<String> strList = new ArrayList<>();
strList.add("str1");
strList.add("str2");
strList.add("str3");
System.out.println(strList.remove(2));
System.out.println(strList.remove(1));
System.out.println(strList.remove(0));
从小角标往大角标删除,可能会导致删除的不是预期元素:
List<String> strList = new ArrayList<>();
strList.add("str1");
strList.add("str2");
strList.add("str3");
System.out.println(strList.remove(0));
System.out.println(strList.remove(1));
更严重的情况,还会出现角标越界:
List<String> strList = new ArrayList<>();
strList.add("str1");
strList.add("str2");
strList.add("str3");
System.out.println(strList.remove(0));
System.out.println(strList.remove(1));
System.out.println(strList.remove(2));
结果:
str1
str3
并且抛出如下异常:
java.lang.IndexOutOfBoundsException: Index: 2, Size: 1
3、集合属于引用传递,使用时一定要注意
原集合:
List<String> strList = new ArrayList<>();
strList.add("str1");
strList.add("str2");
strList.add("str3");
for (String str : strList) {
System.out.println("strList:" + str);
}
结果:
strList:str1
strList:str2
strList:str3
引用传递,调用方法后:
public List<String> addStrList1(List<String> strList) {
strList.add("str4");
strList.add("str5");
return strList;
}
addStrList1(strList);
for (String str : strList) {
System.out.println("strList:" + str);
}
结果:
strList:str1
strList:str2
strList:str3
strList:str4
strList:str5
值传递,调用方法后:
public List<String> addStrList2(List<String> strList) {
List<String> strList2 = new ArrayList<>(strList);
strList2.add("str6");
strList2.add("str7");
return strList2;
}
List<String> strList2 = addStrList2(strList);
for (String str : strList) {
System.out.println("strList:" + str);
}
System.out.println("================================");
for (String str : strList2) {
System.out.println("strList2:" + str);
}
结果:
strList:str1
strList:str2
strList:str3
strList:str4
strList:str5
================================
strList2:str1
strList2:str2
strList2:str3
strList2:str4
strList2:str5
strList2:str6
strList2:str7