集合操作的工具类:
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()方法可用在游戏随机发牌中:
代码:
package com.test;import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Random;//线程安全
public class Main { public static void main(String[] args){ Character[] a ={'1','2','3','4','5','6','7','8','9','J','Q','K'};List<Character> list = new ArrayList<>(Arrays.asList(a));Collections.shuffle(list);for (Character string : list) {System.out.println(string);}}
}