我有一個大小爲5的字符串數組。 這些數組中的5個字符串是動態添加的。我必須在我的程序中顯示這些數組。當第6個元素字符串/新元素字符串出現時,它應該刪除數組中的第5個字符串,並且將新元素添加到第一個位置。其他4個元素應該替換到下一個位置。如何不使用循環可能?動態數組元素操作
Q
動態數組元素操作
-2
A
回答
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);
相關問題
- 1. 在jQuery中操作動態元素
- 2. 使用numpy數組元素的操作
- 3. 一維數組元素上的最近鄰元素操作
- 4. 靜態數組和動態數組中元素的數量
- 5. C++初始化動態數組元素
- 6. 將元素動態添加到數組
- 7. 讓行/動態二維數組元素
- 8. 動態定義數組中的元素
- 9. 動態數組結構,刪除元素
- 10. 將元素動態推入數組[Javascript]
- 11. 動態添加元素到數組
- 12. 動態推送元素到數組jquery
- 13. 操作元組
- 14. C中動態分配數組的數組元素數
- 15. 製作數組元素null
- 16. Python元組操作
- 17. Android佈局:組動態元素
- 18. 添加動態元素時組織DOM
- 19. 動作3:如何訪問在循環中創建的數組元素動態
- 20. 在不改變索引的情況下操作數組元素
- 21. 基於元素操作的迭代數組
- 22. 在numpy字符串數組上執行按元素操作
- 23. 如何使用redux操作數組中的精確元素
- 24. python二維數組中的元素AND或OR操作
- 25. 字符串操作在Python中的數組的所有元素
- 26. jQuery元素值操作
- 27. 操作WPF元素樹
- 28. SELECT元素的JQuery操作
- 29. 結構元素操作(matlab)
- 30. NumPy函數的元素操作比操作符更快嗎?
你應該使用數組 –
的ArrayList的研究所端使用'ArrayList' – AlphaQ
我怎麼能實現呢? @AlphaQ –