[英]ArrayList elements refuse to be removed
因此,我正在制作一個隨機的平假名名稱生成器(不要問為什么,好嗎?),我遇到了一個問題。 隨機名稱生成器在大多數情況下都能正常工作,但有時由於某種原因會生成一長串重復的輔音。 因此,我決定嘗試遍歷ArrayList並在隨機生成后刪除重復的字符,而不是像普通程序員那樣直接解決該問題:
ArrayList<String> name = new ArrayList<String>();
Iterator <String> it = name.iterator();
... // insert random generation here
for (h = 0; h < s; h++) { // s is the length of the ArrayList
...
String curInd = name.get(h);
String nextInd = name.get(h+1);
if (curInd.equals(nextInd)) { // NOT
name.remove(h); // WORKING
s--; // :(
}
}
String previousName = "";
while (it.hasNext()) {
String currentName = it.next();
if (currentName.equals(previousName)) {
it.remove();
}
previousName = currentName;
}
這是行不通的。 我沒有收到錯誤或任何提示,它只是不會刪除重復的字符(或者重復的字符串,因為我將每個字符都設為字符串)。這可能是什么問題?
刪除項目后,您將立即更改索引。 嘗試使用Iterator.remove()
函數,如下所示:
Iterator<String> it = name.iterator();
String previousName = "";
while (it.hasNext()) {
String currentName = it.next();
if (currentName.equals(previousName)) {
it.remove();
}
previousName = currentName;
}
另外,您也可以使用以下一欄刪除所有重復項:
names = new ArrayList<String>(new LinkedHashSet<String>(names));
甚至更好的是,如果您不希望有任何重復項,請從一開始就使用LinkedHashSet
或HashSet
而不是ArrayList
。
您應該使用Iterator.remove
以便在遍歷列表時刪除元素。
索引必須小於List
length
。
String nextInd = name.get(h+1);
上面的語句將拋出IndexOutOfBoundsException
。
使用HashSet,它會自動刪除重復的元素,但會按字母順序對元素進行排序。
對於Arraylist,請嘗試使用它。 這可能會有所幫助。
int size=headlines.size();
for (int i = 0; i < size - 1; i++) {
// start from the next item after strings[i]
// since the ones before are checked
for (int j = i + 1; j < size; j++) {
// no need for if ( i == j ) here
if (!headlines.get(j).equals(headlines.get(i)))
continue;
headlines.remove(j);
// decrease j because the array got re-indexed
j--;
// decrease the size of the array
size--;
} // for j
} // for i
您可以利用某種Set
自動刪除重復的元素,例如...
ArrayList<String> name = new ArrayList<String>();
name.add("A");
name.add("A");
name.add("B");
name.add("B");
name.add("B");
name.add("C");
name.add("C");
name.add("C");
System.out.println(name);
Set<String> set = new TreeSet<String>();
set.addAll(name);
System.out.println(set);
當然,這將刪除所有重復項,而不僅僅是彼此相鄰出現的重復項...
例如...
[A, A, B, B, B, C, C, C]
[A, B, C]
要么...
[A, B, C, B, C, B, C, A]
[A, B, C]
因此它可能無法滿足您的即時需求...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.