數(shù)組的特殊性
數(shù)組與其他種類的容器之間的區(qū)別有三方面:效率争剿、類型和保存基本類型的能力羽利。在Java中,數(shù)組是一種效率最高的存儲和隨機訪問對象引用序列的方式麦到,數(shù)組就是一個簡單的線性序列虹茶,這使得元素訪問非常迅速,但是為這種速度付出的代價就是數(shù)組對象的大小被固定隅要,并且在其生命周期中不可改變蝴罪。
數(shù)組之所以優(yōu)于泛型之前的容器,就是因為你可以創(chuàng)建一個數(shù)組去持有某種具體的類型步清。這意味著你可以通過編譯期檢查要门,來防止插入錯誤類型和抽取不正當?shù)念愋汀?/p>
使用數(shù)組,返回一個數(shù)組
import java.util.*;
public class IceCream {
private static Random rand = new Random(47);
static final String[] FLAVORS = {
"Chocolate", "Strawberry","Mint chip","Rum Raisin","Mud Pie","Mocha","test1","test2","test3"
};
public static String[] flavorSet(int n){
if(n> FLAVORS.length){
throw new IllegalArgumentException("Set too big");
}
String[] results = new String[n];
boolean[] picked = new boolean[FLAVORS.length];
for(int i = 0; i < n; i++){
int t;
do{
t = rand.nextInt(FLAVORS.length);
}while(picked[t]);
results[i] = FLAVORS[t];
picked[t] = true;
}
return results;
}
public static void main(String[] args) {
for (int i = 0; i < 7; i++) {
System.out.println(Arrays.toString(flavorSet(3)));
}
}
}
數(shù)組的協(xié)變
下面的例子來源于Java編程思想
class Fruit {}
class Apple extends Fruit {}
class Jonathan extends Apple {}
class Orange extends Fruit {}
public class CovariantArrays {
public static void main(String[] args) {
Fruit[] fruit = new Apple[10];
fruit[0] = new Apple(); // OK
fruit[1] = new Jonathan(); // OK
// Runtime type is Apple[], not Fruit[] or Orange[]:
try {
// Compiler allows you to add Fruit:
fruit[0] = new Fruit(); // ArrayStoreException
} catch(Exception e) { System.out.println(e); }
try {
// Compiler allows you to add Oranges:
fruit[0] = new Orange(); // ArrayStoreException
} catch(Exception e) { System.out.println(e); }
}
}
main
方法中的第一行廓啊,創(chuàng)建了一個 Apple
數(shù)組并把它賦給 Fruit
數(shù)組的引用欢搜。這是有意義的,Apple
是 Fruit
的子類谴轮,一個 Apple
對象也是一種 Fruit
對象炒瘟,所以一個 Apple
數(shù)組也是一種 Fruit
的數(shù)組。這稱作數(shù)組的協(xié)變第步,Java
把數(shù)組設計為協(xié)變的疮装,對此是有爭議的,有人認為這是一種缺陷粘都。
盡管 Apple[]
可以 “向上轉(zhuǎn)型” 為 Fruit[]
廓推,但數(shù)組元素的實際類型還是Apple
,我們只能向數(shù)組中放入 Apple
或者Apple
的子類翩隧。在上面的代碼中樊展,向數(shù)組中放入了Fruit
對象和 Orange
對象。對于編譯器來說堆生,這是可以通過編譯的专缠,但是在運行時期,JVM
能夠知道數(shù)組的實際類型是 Apple[]
淑仆,所以當其它對象加入數(shù)組的時候就會拋出異常涝婉。