2017-03-05 120 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);