Java中Arrays工具類詳解

來源:互聯網
上載者:User

標籤:不能   www   字串   工具類   highlight   get   結果   tps   可變參   

Arrays是JDK內建的一個數組協助工具輔助類。位於java.util包下

該類有以下特點:

1.無法被建立對象

2.大部分都是靜態方法(好像畫蛇添足了,hh)

下面著重講解asList方法

首先看看源碼:

@SafeVarargspublic static <T> List<T> asList(T... a) {     return new ArrayList<>(a);}

源碼很簡潔,就是給你建立了一個ArrayList,把該數組作為參數傳遞進去。

其實ArrayList底層就是數組。

再深入看看ArrayList中該構造方法

很奇怪Arrays類裡面自己有一個私人的靜態類

 

該構造方法

ArrayList(E[] array) {      if (array==null)          throw new NullPointerException();       a = array;}

這個也很簡潔,直接把傳遞過來的數組給自己的數組a

可是這個Arrays$ArrayList和java.util.ArrayList有什麼區別呢?

借用百度知道heptnaol網友的回答:

不一樣,前者只是為了序列化寫的一個內部類,只有一個參數為數組的建構函式,且沒有add方法,這表示它不能動態擴充內部儲存的數組。

好,我們測試一下asList方法
int[] a1 = new int[]{1,2,3};// 一維數組int[] a2 = new int[]{1,2,3,4};// 一維數組int[][] a3 = new int[][]{{1,2,3},{0,2,3},{2,2,3}};// 二維數組String[] a4 = new String[]{"abc","xyz","kpl"};// 字串數組Object[] a5 = new Object[]{new String("123"),new String("123"),new String("123")};// Object數組System.out.println(Arrays.asList(a1));System.out.println(Arrays.asList(a2));System.out.println(Arrays.asList(a3));System.out.println(Arrays.asList(a4));System.out.println(Arrays.asList(a5));

結果如下:

[[[email protected]][[[email protected]][[[email protected], [[email protected], [[email protected]][abc, xyz, kpl][123, 123, 123]

那麼問題來了,為什麼int數組傳遞進入asList列印仍然是一個數組的地址呢?

  由於int不是類,所以和T(Type,java類)無法匹配,所以編譯器將int[]作為參數傳遞,所以無法解析該數組。

而String數組和Object數組都是裝的對象,所以可以被可變參數拆解成數組。並賦給a數組

不懂?ok,畫個圖形如一下。

關於這個Arrays中的內部類ArrayList目前仍然有不解的地方,JDK開發人員為什麼要這樣設計?還有RandomAccess介面有什麼含義?我將在下一節為大家講解,謝謝。

Java中Arrays工具類詳解

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.