[英]How to Insert string to a particular index in string array and shifting strings after that?
[英]How to append String at particular index in an array of Strings
我有一個如下所示的String
數組:
String[] titles = new String[] { "Booking", "Entry", "Type",
"Duration", "Status", "Contract ID",
"Capacity", "Start Day", "End Day", "Source Ref" };
我需要在以后的狀態下向這個數組附加一些值,如下所示:
titles = new String[] { "Booking", "Shipper", "Booking Quantity", "Entry",
"Type", "Duration", "Status",
"Contract ID", "Capacity", "Start Day",
"End Day", "Source Ref" };
在這里,我將"Shipper", "Booking Quantity"
到第一個陣列。
有沒有辦法基於索引或任何方式附加這些值,而不創建像上面的例子? (可能嗎?)
也許我沒有解決你的問題,但你可以使用ArrayList<String>
而不是簡單的數組。 你可以這樣做:
titles.add(1, "Shipper");
titles.add(2, "Book Quantity");
所以你基本上將標題的ArrayList<String>
添加到位置1和2的兩個新元素。
不,你不能用普通數組做到這一點。
當你初始化這樣的數組時
String[] titles = new String[] { "Booking", "Entry", "Type",
"Duration", "Status", "Contract ID",
"Capacity", "Start Day", "End Day", "Source Ref" };
數組的屬性“一旦你初始化數組之后就不能改變數組的大小”*
所以在你的情況下你必須初始化新的數組....
或者您可以使用ArrayList
及其add(index, value)
方法,您可以在所需位置添加值。
但隱含它也使用Concept of Dynamic Array..
不,你不能。 數組不是動態的。 您需要創建一個新數組。 在創建數組之前必須知道大小。
String[] strings = new String[titles.length + 2];
strings[0] = "Booking";
strings[1] = "Shipper";
//...
要根據索引添加它們,您實際上需要創建一個新數組並映射舊數組中的所有值,並隨時添加新值。
如果您使用的是ArrayList ,它會更容易,它具有可以在List中的任何索引處插入新值的insert
方法
例如:
ArrayList<String> myList = new ArrayList<>();
myList.add("Booking");
myList.add("Entry");
myList.add("Type");
myList.add("Duration");
myList.add("Status");
myList.add("Contract ID");
myList.add("Capacity");
myList.add("Start Day");
myList.add("End Day");
myList.add("Source Ref");
//insertion
myList.add(1, "Shipper");
mylist.add(2, "Booking Quantity");
您可以將字符串保存在ArrayList<String>
,然后使用.add(index, text)
方法
最好使用List<String>
並使用add()
方法。
您可以使用ArrayList,如下所示:
ArrayList titleList = new ArrayList<String>();
titleList.add("Shipper");
titleList.add("Booking");
titleList.add("Entry");
titleList.add("Type");
titleList.add("Duration");
titleList.add("Status");
titleList.add("Contract");
titleList.add("ID");
//....
titleList.add(1,"Shipper")
titleList.add(2,"Booking quality");
使用ArrayList的好處是您可以使用Iterator並執行各種操作,例如搜索特定條目。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.