我写了这个代码:
public String[] removeDuplicates(String[] input){
int i;
int j;
int dups = 0;
int array_length = input.length;
for(i=0; i < array_length; i++){
//check whether it occurs more than once
for(j=0; j < array_length; j++){
if (input[i] == input[j] && i != j){
dups++; //set duplicates boolean true
input[j] = null; //remove second occurence
} //if cond
} // for j
} // for i
System.out.println("Category contained " + dups + " duplicates.");
return input;
}
这是为了检查是否字符串数组包含一个或多个重复项。但是,即使当我这样定义数组时:
String[] temp = new String[2];
temp[0] = "a";
temp[1] = "a";
if条件未被“触发”。我误解了如何& &的作品?在我看来,程序应该首先检查两个字符串是否相同(它们是...),然后检查两个索引是否相同。如果不是,它应该执行操作。 但是,程序似乎认为不然。
没有直接关系删除重复的,但你可以加快这通过初始化J =我,因为你显然不需要重新测试下部串。你还应该在比较之前检查输入[i]是否为空... – sybkar
你甚至可以避免检查'i!= j'。您只需将'j'初始化为'i + 1'。所以第二个for循环看起来像︰for(j = i + 1; j
Nejc