2013-08-18 31 views
1

我有一個問題,選擇哪種數組用於這種情況。有許多數組像列表,集合和其他。我想在數組中保留這樣的兩個數字(這裏的數字是隨機的): (多行和2列)。這個案例的最佳陣列

2, 4 
4, 8 
8, 7 
... 

但也有這個數組的功能,很容易把第一個數組行,並把它放在最後。你可以建議我在這種情況下使用什麼?

p.s.即時通訊新的,所以我想選擇最好的選擇,這就是爲什麼在這裏。

+0

你在問一般的數據結構;數組只是一種特定的結構。你用它做什麼? – chrylis

+3

只有一個數組 - 數組。您提到的所有其他「數組」都稱爲「集合」。 – dasblinkenlight

+0

對於您的特殊情況,請嘗試使用HashMaps。 :) – user2339071

回答

2

取決於你說什麼容易。易於編程或高性能。 既然你是新人,我想你正在尋找第一個。我要堅持的ArrayList<Integer>ArrayList<Pair<Integer, Integer>>,其中一對是一個自定義類這樣的:

public class Pair<A, B> 
{ 
    public Pair(A a, B b) { this.a = a; this.b = b; } 
    public A a; 
    public B b; 
} 

然後,使用這樣的:

List<Pair<Integer, Integer>> list = new ArrayList<Pair<Integer, Integer>>(); 
list.add(new Pair<Integer, Integer>(3, 5)); 
list.add(new Pair<Integer, Integer>(7, 1)); 
// now take the first and put it at the end: 
list.add(list.remove(0)); 

編輯:如果移動的第一個元素的表現到最後是瓶頸,你希望它快速發展,那麼使用LinkedList。這將是O(1)操作,而使用ArrayList進行操作時,它將是O(n)操作。

3

你最好創建一個類,比如說,Pair

class Pair { 
    private int i1; 
    private int i2; 

    public Pair(int i1, int i2) { this.i1 = i1; this.i2 = i2; } 

    public int getI1() { return i1; } 

    public int getI2() { return i2; } 
} 

然後根據您的特殊需求ArrayList<Pair>HashSet<Pair>等之間進行選擇。

+0

嗯我已經做了類似的早些時候與其他類也許它會工作,謝謝我會嘗試 –

+0

+1:事實上,我喜歡非泛型版本,因爲JVM會不斷箱和取消箱。 –

1

首先,你是在談論集合,而不是數組:數組是一種特定的集合,並且是最原始的集合。您應該在創建集合時已知集合中元素的數量時直接使用數組,並且在此之後永遠不會更改。

如果您的要求是從一個集合的開頭刪除一個元素並在最後插入一個元素,那麼您應該使用Queue<T>LinkedList<T>,並將一個對象表示該對數字的泛型類型參數。這些數據結構經過優化,可以快速插入和從端點移除。