ArrayList元素拒绝被删除

Cof*_*ker 1 java arraylist

所以,我正在制作一个随机的平假名发生器(不要问为什么,好吗?)并且我遇到了一些问题.随机名称生成器在大多数情况下工作正常但有时由于某种原因它会生成长串的重复辅音.因此,我没有像普通程序员那样直接解决问题,而是决定尝试扫描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;
}
Run Code Online (Sandbox Code Playgroud)

这不起作用.我没有收到错误或其他任何内容,它只是不会删除重复的字符(或者更确切地说是重复的字符串,因为我将每个字符都设置为字符串.)可能是什么问题?

Sam*_*ley 5

删除项目后,您将立即更改索引.尝试使用Iterator.remove()功能:

Iterator<String> it = name.iterator();
String previousName = "";

while (it.hasNext()) {
    String currentName = it.next();
    if (currentName.equals(previousName)) {
        it.remove();
    }
    previousName = currentName;
}
Run Code Online (Sandbox Code Playgroud)

或者你可以删除所有使用以下单行重复项:

names = new ArrayList<String>(new LinkedHashSet<String>(names));
Run Code Online (Sandbox Code Playgroud)

或者甚至更好,如果你不想要任何重复,从一开始就使用LinkedHashSetHashSet代替ArrayList.