可能重复:
如何比较Java中的字符串?
我写了这段代码:
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;
}
Run Code Online (Sandbox Code Playgroud)
应该检查一个字符串数组是否包含一个或多个重复项.但是,即使我像这样定义数组:
String[] temp = new String[2];
temp[0] = "a";
temp[1] = "a";
Run Code Online (Sandbox Code Playgroud)
if条件不是"触发"的.我是否误解了&&如何运作?在我看来,程序应首先检查两个字符串是否相同(它们是......),然后检查两个索引是否相同.如果没有,它应该执行操作.但是,程序似乎不这么认为.
Java中最常见的错误之一是假设a String是对象的引用时的对象.当您使用时,==您正在比较参考,而不是它们的内容.这就是为什么.equals()需要比较它们的内容.
顺便说一句,你可以删除重复
public static String[] removeDuplicates(String[] input){
return new HashSet<String>(Arrays.asList(input)).toArray(new String[0]);
}
Run Code Online (Sandbox Code Playgroud)