集合的工具类
集合操作的工具類:
1):Arrays類:
2):Collections類.
Arrays類:
在Collection接口中有一個方法叫toArray把集合轉換為Object數組.
把集合轉換為數組: Object[] arr = 集合對象.toArray();
數組也可以轉換為集合(List集合):
public static List asList(T… a) 等價于public static List asList(T[] a).
通過Arrays.asList方法得到的List對象的長度是固定的,不能增,也不能減.
為什么: asList方法返回的ArrayList對象,不是java.util.ArrayList而是Arrays類中的內部類對象.
面試題:Collection和Collections的區別.
Collections類:封裝了Set,List,Map的操作的工具方法.
獲取空集對象(沒有元素的集合,注意集合不為null):
常用的集合類:
HashSet/ArrayList/HashMap都是線程不安全的,在多線程環境下不安全.
在Collections類中有獲取線程安全的集合方法:
List list = Collections.synchronizedList(new ArrayList());
當要做迭代的時候得使用synchronized.
synchronized(list) {
TODO
}
Set set = Collections.synchronizedSet(new HashSet());
Map map = Collections.synchronizedMap(new HashMap());
Java.util.Collections類下有一個靜態的shuffle()方法,如下:
1)static void shuffle(List
package ahu; import java.util.*; public class Modify { public static void main(String[] args){ Random rand=new Random(47); Integer[] ia={0,1,2,3,4,5,6,7,8,9}; List<Integer> list=new ArrayList<Integer>(Arrays.asList(ia)); System.out.println("Before shufflig: "+list); Collections.shuffle(list,rand); System.out.println("After shuffling: "+list); System.out.println("array: "+Arrays.toString(ia)); List<Integer> list1=Arrays.asList(ia); System.out.println("Before shuffling: "+list1); Collections.shuffle(list1,rand); System.out.println("After shuffling: "+list1); System.out.println("array: "+Arrays.toString(ia)); } }output:
Before shufflig: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] After shuffling: [3, 5, 2, 0, 7, 6, 1, 4, 9, 8] array: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] Before shuffling: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] After shuffling: [8, 0, 5, 2, 6, 1, 4, 9, 3, 7] array: [8, 0, 5, 2, 6, 1, 4, 9, 3, 7]Collections.shuffle()方法可用在游戲隨機發牌中:
代碼:
總結
- 上一篇: nodejs异步读取文件与同步读取文件的
- 下一篇: node.js文件操作