使用集合轉數組的方法,必須使用集合的 toArray(T[] array),傳入的是類型完全一樣的數組,大小就是 list.size()。
反例:直接使用 toArray 無參方法存在問題,此方法返回值只能是 Object[] 類,若強轉其它類型數組將出現 ClassCastException 錯誤。
反例:
1
2
3
4
5
6
7
8
|
public static void main(String[] args) throws Exception { List<String> list = new ArrayList<String>(); list.add( "A" ); list.add( "B" ); list.add( "C" ); String[] array = (String[])list.toArray(); } |
異常:
Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;
正例:
1
2
3
4
5
6
7
8
9
10
|
public static void main(String[] args) throws Exception { List<String> list = new ArrayList<String>(); list.add( "A" ); list.add( "B" ); list.add( "C" ); // 使用泛型,無需顯式類型轉換 String[] array = list.toArray( new String[list.size()]); System.out.println(array[ 0 ]); } |
Array 轉 List
使用工具類 Arrays.asList() 把數組轉換成集合時,不能使用其修改集合相關的方法,它的 add/remove/clear 方法會拋出 UnsupportedOperationException 異常。
說明:asList 的返回對象是一個 Arrays 內部類,并沒有實現集合的修改方法。Arrays.asList體現的是適配器模式,只是轉換接口,后臺的數據仍是數組。
1
2
|
String[] str = new String[] { "a" , "b" }; List list = Arrays.asList(str); |
第一種情況:list.add("c"); 運行時異常。
1
|
Exception in thread "main" java.lang.UnsupportedOperationException |
第二種情況:list[0]= "gujin"; 那么 list.get(0) 也會隨之修改。
說明:
1
2
3
4
5
|
@SafeVarargs @SuppressWarnings ( "varargs" ) public static <T> List<T> asList(T... a) { return new ArrayList<>(a); } |
這個 ArrayList 并不是 java.util 中的 ArrayList,而是一個內部的 ArrayList,不提供 add 等修改操作。
1
2
3
4
5
|
private static class ArrayList<E> extends AbstractList<E> implements RandomAccess, java.io.Serializable { private static final long serialVersionUID = -2764017481108945198L; private final E[] a; |
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:http://www.jianshu.com/p/ce3b6355f7ee