java使用Collection單例集合實現(xiàn)元素存儲
/**
* ?使用List/Set存儲[1,10]整數(shù)1到10 不重復(fù),放入順序隨機
*/
public class TestList {
? ?public static void main(String[] args) {
? ? ? ?List<Integer> al = new ArrayList<>();
? ? ? ?Random r = new Random();
? ? ? ?int count=0;
? ? ? ?while(al.size()<10){
? ? ? ? ? ?Integer e = r.nextInt(10)+1;
? ? ? ? ? ?//.nextInt(10)返回0到9整數(shù),再+1變?yōu)?到10
? ? ? ? ? ?if (!al.contains(e)){
? ? ? ? ? ? ? ?//List允許元素重復(fù) 需要在添加之前判斷.contains()
? ? ? ? ? ? ? ?al.add(e);
? ? ? ? ? ?}
? ? ? ? ? ?count++;
? ? ? ?}
? ? ? ?System.out.println(al);
? ? ? ?//結(jié)果[8, 10, 6, 7, 4, 5, 2, 3, 9, 1] List不會自動對容器內(nèi)的元素更改順序/排序 每個存入的元素都有index index是從0開始順序的
? ? ? ?System.out.println(count);
? ?}
}
class TestSet{
? ?public static void main(String[] args) {
? ? ? ?Set<Integer> hs = new HashSet<>();
? ? ? ?int count = 0;
? ? ? ?while (hs.size()<10){
? ? ? ? ? ?hs.add((int)(Math.random()*10+1));
? ? ? ? ? ?count++;
? ? ? ? ? ?//Set集合要求元素互異 存入重復(fù)元素會被舍棄
? ? ? ?}
? ? ? ?System.out.println(hs);
? ? ? ?//結(jié)果[1, 2, 3, 4, 5, 6, 7, 8, 9, 10] HashSet偽排序 初始通過[16]長度數(shù)組+單向鏈表進行存儲 每個元素需要.hashCode()返回結(jié)果%16 存放到對應(yīng)的位置
? ? ? ?//Integer重寫.hashCode()直接return value ?1到10%16結(jié)果為1到10 遍歷時從前往后依次取出 結(jié)果恰好為從小到大順序
? ? ? ?System.out.println(count);
? ? ? ?hs.add(16);
? ? ? ?System.out.println(hs);
? ? ? ?//結(jié)果[16, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] ?16%16=0 存放到1的前面 遍歷的時候元素的順序不再有序
? ?}
}