(1)數組是大小固定的,并且同一個數組只能存放類型一樣的數據(基本類型/引用類型)
(2)JAVA集合可以存儲和操作數目不固定的一組數據。(3)若程序時不知道究竟需要多少對象,需要在空間不足時自動擴增容量,則需要使用容器類庫,array不適用。
聯系:使用相應的toArray()和Arrays.asList()方法可以回想轉換。
List和ArrayList的區別
1.List是接口,List特性就是有序,會確保以一定的順序保存元素.
ArrayList是它的實現類,是一個用數組實現的List.
Map是接口,Map特性就是根據一個對象查找對象.
HashMap是它的實現類,HashMap用hash表實現的Map,就是利用對象的hashcode(hashcode()是Object的方法)進行快速散列查找.(關于散列查找,可以參看<<數據結構>>)
2.一般情況下,如果沒有必要,推薦代碼只同List,Map接口打交道.
比如:Listlist=newArrayList();
這樣做的原因是list就相當于是一個泛型的實現,如果想改變list的類型,只需要:
Listlist=newLinkedList();//LinkedList也是List的實現類,也是ArrayList的兄弟類
這樣,就不需要修改其它代碼,這就是接口編程的優雅之處.
另外的例子就是,在類的方法中,如下聲明:
privatevoiddoMyAction(Listlist){}
這樣這個方法能處理所有實現了List接口的類,一定程度上實現了泛型函數.
3.如果開發的時候覺得ArrayList,HashMap的性能不能滿足你的需要,可以通過實現List,Map(或者Collection)來定制你的自定義類.
List,Set轉換為數組的方法
toArray函數有兩種形式,一種無參數,一種帶參數,注意帶參數形式中,要指明數組的大小。
程序代碼:
1
2
3
4
5
6
7
8
|
public void convertCollectionToArray() { List list = new ArrayList(); Object[] objectArray1 = list.toArray(); String[] array1 = list.toArray( new String[list.size()]); Set set = new HashSet(); Object[] objectArray2 = set.toArray(); String[] array2 = set.toArray( new String[set.size()]); } |
反過來,數組轉換為List,Set。
1
2
3
4
5
|
Integer[] numbers = { 7 , 7 , 8 , 9 , 10 , 8 , 8 , 9 , 6 , 5 , 4 }; // To convert an array into a Set first we convert it to a List. Next // with the list we create a HashSet and pass the list as the constructor. List list = Arrays.asList(numbers); Set set = new HashSet(list); |
注意:對于int[]數組不能直接這樣做,因為asList()方法的參數必須是對象。應該先把int[]轉化為Integer[]。對于其他primitive類型的數組也是如此,必須先轉換成相應的wrapper類型數組。
1
2
3
4
5
6
7
8
|
int [] numbers = { 7 , 7 , 8 , 9 , 10 , 8 , 8 , 9 , 6 , 5 , 4 }; int size = numbers.length; Integer[] array = new Integer[size]; for ( int i = 0 ; i < numbers.length; i++) { Integer integer = numbers[i]; array[i] = integer; } List list = Arrays.asList(array); |
總結
以上就是本文關于Java集合與數組區別簡介及相互轉換實例的全部內容,希望對大家有所幫助。如有不足之處,歡迎留言指出。感謝朋友們對本站的支持!
原文鏈接:https://www.cnblogs.com/annieBaby/p/4889406.html