2014-04-17 15 views
2

我想在java中製作一個通用數組 - 我在哪些方面遇到一些問題 - 我如何製作一個大小爲6的元組數組,其大小爲一個字節[]和一個整數裏面?在java中創建一個通用數組

感謝

private Tuple<byte[], Integer>[] alternativeImages1 = new Tuple<byte[], Integer>[6]; 

class Tuple<F, S> { 

    public final F first; 
    public final S second; 

    public Tuple(final F first, final S second) { 
     this.first = first; 
     this.second = second; 
    } 

    @Override 
    public boolean equals(final Object o) { 
     if (this == o) 
      return true; 
     if (o == null || getClass() != o.getClass()) 
      return false; 

     final Tuple tuple = (Tuple) o; 
     return this.first == tuple.first && this.second == tuple.second; 
    } 

    @Override 
    public int hashCode() { 
     int result = this.first != null ? first.hashCode() : 0; 
     result = 31 * result + (this.second != null ? second.hashCode() : 0); 
     return result; 
    } 
} 
+0

您不能創建帶有類型參數的類型的數組;這是Java中數組的限制。這個問題之前已經被問過,例如:[Array of Generic List](http://stackoverflow.com/questions/7810074/array-of-generic-list) – Jesper

回答

7

那麼你可以使用原始類型:

Tuple[] array = new Tuple[6]; 

或者你也可以讓一個未經檢查的轉換:

Tuple<byte[], Integer>[] array = (Tuple<byte[], Integer>[])new Tuple[6]; 

// or just this because raw types let you do it 
Tuple<byte[], Integer>[] array = new Tuple[6]; 

或者你可以使用一個列表,而不是:

List<Tuple<byte[], Integer>> list = new ArrayList<Tuple<byte[], Integer>>(); 

我推薦使用List來代替。

在前兩個選項之間進行選擇時,我會推薦未經檢查的轉換,因爲它會爲您提供編譯時檢查。但是,如果你在其中添加了一些其他類型的元組,它不會拋出ArrayStoreException。

+0

如果你可以使用固定大小的列表而不需要限制檢查然後我會使用我認爲的列表(特別是如果我可以刪除默認的空值) – Biscuit128

+0

嗯,這是真的列表有一些不同的數組功能。儘管可以擴展ArrayList並使其表現得更像一個數組。我可以給你一個例子,如果你想,但我建議你習慣使用List的功能。它通常比較好,除了低級處理(如I/O)或固定長度重要的數據結構(如散列表)外,幾乎沒有理由使用數組。 – Radiodef

相關問題