P217泛型和類型安全的容器
不顯示指定泛型的將自動繼承自Object,此時容器可裝任何類型的類,取出時需強制轉換為指定的類型。
public class ApplesAndOrangesWithoutGenerics {
@SuppressWarnings("unchecked")
public static void main(String[] args) {
ArrayList arrayList = new ArrayList();
for (int i = 0; i < 3; i++)
arrayList.add(new Apple());
arrayList.add(new Orage());
for (int i=0;i<arrayList.size();i++)
System.out.println(((Apple)arrayList.get(i)).getId()); //最后一個取值報錯
}
}
class Apple {
private static long counter;
private final long id = counter++;
public long getId() {
return id;
}
}
class Orage {
}
結果
0
1
2
Exception in thread "main" java.lang.ClassCastException: eleven.Orage cannot be cast to eleven.Apple at eleven.ApplesAndOrangesWithoutGenerics.main(ApplesAndOrangesWithoutGenerics.java:15)
P220添加一組元素
/**
* Arrays.asList():接收一個數組或者是用逗號分隔的元素列表
* Collections.addAll():接收一個Collection對象、一個數組、用都逗號分隔的列表 傳統的addAll()方法
*/
public class AboutAsListAddAll {
public static void main(String[] args) {
Integer[] ints = { 1, 2, 3, 4, 5 };
Collection<Integer> collection = new ArrayList<Integer>(Arrays.asList(ints));
// 只能接收另一個Collection對象作為參數,不靈活
collection.addAll(Arrays.asList(6, 7, 8, 9, 10));
Collections.addAll(collection, 11, 12, 13, 14, 15); // 這個快,首選
Collections.addAll(collection, ints);
print(collection);
List<Integer> list = Arrays.asList(ints);
list.set(0, 0); //將數組第一個元素設置成0,能改變ints的值
print(list);
//會有運行時錯誤,底層表示為數組,不能調整尺寸
// list.add(1);
List<Integer> list2 = new ArrayList<Integer>();
list2.addAll(Arrays.asList(ints));
list2.add(6);
print(list2);
}
public static void print(Collection<Integer> c) {
for (Integer i : c) System.out.print(i + " ");
System.out.println();
}
}
結果
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 1 2 3 4 5
0 2 3 4 5
0 2 3 4 5 6
P222
容器的區別
-
List:
以特定的順序保存元素- ArrayList:
取快,存慢 - LinkedList:
取慢,存快
- ArrayList:
-
Set:
元素不能重復- HashSet:
最快的取元素方式,順序無意義 - TreeSet:
按照升序保存對象 - LinkedHashSet:
添加順序
- HashSet:
Queue:
在一端進,并從另一端出。-
Map:
關系數組,保存鍵值對- HashMap
- TreeMap
- LinkedHashMap
按照添加順序保存鍵值,還保留了HashMap的速度
P234 Map統計隨機數生成的分布
public class Statistics {
public static void main(String[] args) {
Random rand = new Random(47);
Map<Integer, Integer> m = new TreeMap<Integer, Integer>();
for (int i = 0; i < 1000; i++) {
int r = rand.nextInt(20);
Integer freq = m.get(r);
m.put(r, freq == null ? 1 : freq + 1);
}
System.out.println(m);
}
}
結果
{0=42, 1=44, 2=53, 3=43, 4=44, 5=53, 6=42, 7=53, 8=46, 9=56, 10=58, 11=55, 12=48, 13=55, 14=52, 15=50, 16=53, 17=50, 18=51, 19=52}
這是空白頁