2017-03-05 117 views
-2

我有一個大小爲5的字符串數組。 這些數組中的5個字符串是動態添加的。我必須在我的程序中顯示這些數組。當第6個元素字符串/新元素字符串出現時,它應該刪除數組中的第5個字符串,並且將新元素添加到第一個位置。其他4個元素應該替換到下一個位置。如何不使用循環可能?動態數組元素操作

+0

你應該使用數組 –

+0

的ArrayList的研究所端使用'ArrayList' – AlphaQ

+0

我怎麼能實現呢? @AlphaQ –

回答

0

這是使用ArrayList中的範例:

private void methodName() { 
     //Initialize arraylist 
     ArrayList<String> stringArray = new ArrayList<>(); 

     //Dynamically add the first 5 items 
     stringArray.add("String1"); 
     stringArray.add("String2"); 
     stringArray.add("String3"); 
     stringArray.add("String4"); 
     stringArray.add("String5"); 

     //When a new item comes in (the 6th one), remove the last item and add the new item to the beginning 
     stringArray.remove(stringArray.size()-1); 
     stringArray.add(0, "String6"); 
    } 
0

沒有for循環?要做到這一點,你必須使用ArrayList或類似的工具。示例:

ArrayList<String> array = new ArrayList<>(); 
    array.add("String"); 
    //repeat 4 more times 
    array.clear();//removes all the objects 
    or do 
    array.remove([insert index]);//0-4 or array.size() -1 to get the last or see how much the max is 
    array.add("new string");//you have now replaced the string you removed 

儘管在某些情況下使用循環更容易,但您可以避免使用for-loops。

0

請參考以下代碼以及有關ArrayList的進一步參考的JAVA文檔。

List<String> list = new ArrayList<>(); 
//add values dynamically 

list.remove(list.size() - 1); //remove last element 

//let str be the new element 
list.add(0, str);