2016-04-27 56 views
0

在我對數組和ArrayList的繼續教育中,我試圖通過將ArrayList從一個方法傳遞給另一個方法來實現我的代碼。這裏是我的代碼:在方法之間傳遞ArrayList

public void exampleArrayList() { 
    ArrayList<String> al = new ArrayList<String>(); 
    al.add("AZ"); 
    al.add("BY"); 
    al.add("CX"); 
    al.add("DW"); 
    al.add("EV"); 
    al.add("FU"); 
    al.add("GT"); 

    display(al); 
} 

public void display(ArrayList al) { 

    System.out.println("Index of 'AZ': " + al.indexOf("AZ")); 
    System.out.println("Index of 'FU': " + al.indexOf("FU")); 
    System.out.println("Index of 'AA': " + al.indexOf("AA")); 
    System.out.println("Index of 'CX': " + al.indexOf("CX")); 

    // for (String row : al) 
    // System.out.println("Value at Index " + al.indexOf(row) + 
    //  " is " + al.get(al.indexOf(row))); 

    for(int i = 0; i < al.size(); i++) 
     System.out.println("Value at Index " + al.indexOf(i) + 
      " is " + al.get(al.indexOf(i))); 
} 

在顯示方法適用於兩個語句註釋掉。當前註釋掉的for語句不起作用,因爲row正在查找一個String,但即使數組al是一個字符串,get也會分配一個對象。我是否需要將al投入字符串或其他內容?當我使用創建ArrayList的同一個方法運行for循環時,情況並非如此,我不瞭解它們之間的區別。

第二個for語句沒有被註釋掉導致系統崩潰給我以下運行時錯誤:

java.lang.ArrayIndexOutOfBoundsException: length=12; index=-1 

我試圖改變i < al.size()的硬編碼數,它還是沒有,我不知道爲什麼。

+2

原始類型?爲什麼? – bcsb1001

+0

我想你的意思是「價值在指數'我'是'al.get(i)'」? –

+0

準確的板球。只是把自己綁在想着它的結上。 – Airfix

回答

3

1)你必須把它作爲一個ArrayList<String>

public void display(ArrayList<String> al) { 
          ^^^^^^^^ 

2)你要搜索列表中的整數。該列表不包含任何整數,因此indexOf返回-1。然後你打電話al.get(-1)其中-1明顯超出界限。我不確定你打算在這裏做什麼。

+0

這正是我需要知道的。將其作爲字符串傳遞。然後我看到我對索引的明顯錯誤,因爲我在腦海中混合了兩種不同的代碼。我想,休息一下吧。謝謝您的幫助。慢慢地,這件事開始有意義。 Airfix膨脹。 – Airfix

1

您使用的是indexOf(),如果列表中包含它,則會給出int將搜索該int並返回其索引。由於情況並非如此 - 它是一個List<String> - 由於您試圖檢索索引-1處的元素,因此索引超出範圍。如果無法找到該元素,則返回-1,否則返回indexOf()

這就是爲什麼你不應該使用原始類型。使用get()List<String>爲您的參數(無需使它特別ArrayList S):

System.out.println("Value at Index " + i + 
    " is " + al.get(i)); 

public void display(ArrayList<String> al) { 
1

的另一件事來「變得聰明代碼」是不使用的具體實施在聲明或參數中。

public void exampleArrayList() { 
    // use the interface List<T>, not the specific implementation ArrayList<T> 
    List<String> al = new ArrayList<String>(); 

    ... 
} 

// take the Interface, and give it the type 
public void display(List<String> al) { 
    .... 
} 

功能將是相同的,但它是編程到接口而不是實現的更好的編程方法。

編輯:另外,除非你真的需要索引出於某種原因,使用增強的for循環可能更適合

for (String s : al) { 
    //some operation 
} 
+0

如果我理解第一條評論ArrayList是一個List的實現,那麼基本上說我沒有調用實現(我不明白在我的Java基礎知識水平上)還是有更多的靈活性。關於增強循環,我來自Fortran,C和Visual basic basic的基礎知識,所以這是我最重要的編程方法,我仍然在學習繩索。如果有疑問,我會迴歸我的根。 – Airfix

+1

@Airfix,[Programming to interfaces](http://stackoverflow.com/questions/383947/what-does-it-mean-to-program-to-an-interface)具有許多好處,如答案所示。 [另見這裏](http://www.fatagnus.com/program-to-an-interface-not-an-implementation/)。通常,如果需要,您希望保留更改實施的能力。今天你有一個'ArrayList',但是明天''LinkedList'可能更合適。如果參數中有'List ',則可以調整實現,而其他代碼不知道。 – KevinO