數組之---數組為什麼特殊?

來源:互聯網
上載者:User

標籤:java   數組   數組與容器的區別   

數組為什麼特殊?

Java中大量其他的方式可以持有對象,那麼,到底是什麼使數組變得與眾不同呢?

數組與其他種類的容器之間的區別有三方面:

效率

類型

儲存基本類型的能力

與眾不同的原因?
泛型之前:

在泛型之前,其他的容器類在處理對象時,都將它們是做沒有任何具體類型。也就是說,

它們將這些對象都當做Java中所有類的根類Object處理。數組之所以優於泛型之前的容器,

就是因為你可以建立一個數組去持有某種具體類型,這意味著你可以通過編譯器檢查,防止錯誤類型和抽取不當類型。

數組可以持有基本類型,而泛型之前的容器則不能。

泛型之後:

有了泛型,容器就可以指定並檢查它們所持有對象的類型,並且有了自動封裝機制,因此,容器看起來還是能夠持有基本類型。

我們看一個Demo。

class BerylliumSphere {private static long counter;// 靜態變數是屬於類的,且唯一。private final long id = counter++;// final變數值不可以被改變public String toString() {return "Sphere " + id;}}public class Main {public static void main(String[] args) {/** *對象數組 * */BerylliumSphere[] spheres = new BerylliumSphere[10]; // 建立一個數組對象,數組內引用被初始化為NULL// [null, null, null, null, null, null, null, null, null, null]System.out.println(Arrays.toString(spheres));// 在堆中建立對象,交給數組的引用for (int i = 0; i < 5; i++) {spheres[i] = new BerylliumSphere();}// [Sphere 0, Sphere 1, Sphere 2, Sphere 3, Sphere 4, null, null, null, null, null]System.out.println(Arrays.toString(spheres));// Sphere 4System.out.println(spheres[4]);/** * 容器 * */List<BerylliumSphere> sphereList = new ArrayList<BerylliumSphere>();// []System.out.println(sphereList);for (int i = 0; i < 5; i++) {sphereList.add(new BerylliumSphere());}// [Sphere 5, Sphere 6, Sphere 7, Sphere 8, Sphere 9]System.out.println(sphereList);// Sphere 9System.out.println(sphereList.get(4));/** * 原始類型數組 * */int[] integers = {0, 1, 2, 3, 4, 5};// [0, 1, 2, 3, 4, 5]System.out.println(Arrays.toString(integers));// 4System.out.println(integers[4]);/** * 原始類型容器 * */List<Integer> intList = new ArrayList<Integer>(Arrays.asList(0,1,2,3,4,5));intList.add(97);// [0, 1, 2, 3, 4, 5, 97]System.out.println(intList);// 4System.out.println(intList.get(4));}}

結果:

隨著自動封裝機制的出現,容器已經可以與數組幾乎一樣方便的用於基本類型中了。

數組碩果僅存的有點就是效率。然而,如果要解決更一般化的問題,那數組就可能會受到過多的限制,因此這種情況下,你還是會使用容器。


數組之---數組為什麼特殊?

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.