2014-03-24 23 views
11

我在想,如何將元素追加到Java中ArrayList的末尾?這裏是我到目前爲止的代碼:如何追加Java中ArrayList結尾的元素?

public class Stack { 

    private ArrayList<String> stringList = new ArrayList<String>(); 

    RandomStringGenerator rsg = new RandomStringGenerator(); 

    private void push(){ 
     String random = rsg.randomStringGenerator(); 
     ArrayList.add(random); 
    } 

} 

「randomStringGenerator」是一種生成隨機String的方法。

我基本上想要總是在ArrayList的末尾添加隨機字符串,很像堆棧(因此名稱爲「push」)。

非常感謝你的時間!

+2

使用'stringList.add'。它被「追加」到最後.. – Maroun

+3

你認爲這是什麼 - 'ArrayList.add(random);'會做什麼?它將添加哪個數組列表? –

+1

如果你想要一個像堆棧一樣的東西,爲什麼不使用堆棧? –

回答

20

下面是語法,以及一些其他的方法可能對您有用:

//add to the end of the list 
    stringList.add(random); 

    //add to the beginning of the list 
    stringList.add(0, random); 

    //replace the element at index 4 with random 
    stringList.set(4, random); 

    //remove the element at index 5 
    stringList.remove(5); 

    //remove all elements from the list 
    stringList.clear(); 
0

我知道這是一個老問題,但我想使自己的答案。這裏是另一種方法來做到這一點,如果你「真的」想添加到列表的末尾,而不是使用list.add(str)你可以這樣做,但我不建議。

String[] items = new String[]{"Hello", "World"}; 
     ArrayList<String> list = new ArrayList<>(); 
     Collections.addAll(list, items); 
     int endOfList = list.size(); 
     list.add(endOfList, "This goes end of list"); 
     System.out.println(Collections.singletonList(list)); 

這是將項目添加到列表末尾的'緊湊'方式。 這裏是一個更安全的方式來做到這一點,空檢查和更多。

String[] items = new String[]{"Hello", "World"}; 
     ArrayList<String> list = new ArrayList<>(); 
     Collections.addAll(list, items); 
     addEndOfList(list, "Safer way"); 
     System.out.println(Collections.singletonList(list)); 

private static void addEndOfList(List<String> list, String item){ 
      try{ 
       list.add(getEndOfList(list), item); 
      } catch (IndexOutOfBoundsException e){ 
       System.out.println(e.toString()); 
      } 
     } 

    private static int getEndOfList(List<String> list){ 
     if(list != null) { 
      return list.size(); 
     } 
     return -1; 
    } 

繼承人另一種方式將項目添加到列表的末尾,快樂編碼:)