This question already has answers here:
How do I compare strings in Java?
                                
                                    (23个答案)
                                
                        
                        
                            What is a NullPointerException, and how do I fix it?
                                
                                    (12个答案)
                                
                        
                2年前关闭。
            
        

所以我有看起来像这样的String数组:

arraySubs:

math
math
math
web
web
web
prog
prog
prog


现在,我要删除重复项,如下所示:

arraySubs:

math
web
prog


我不介意应删除的地方是否为空,所以我尝试了以下方法:

for(int j = 0; j < arraySubs.length; j++) {
    if(j<arraySubs.length-1) {
        if(arraySubs[j+1]==arraySubs[j]) {//equalsIgnoreCase doesn't work.
            arraySubs[j]=null;
        }
    }
    if(arraySubs[j]!=null) {
        System.out.println(arraySubs[j]);
    }
}


但这仍然行不通,仍然打印所有这些,有什么想法吗?
我不想使用Set,HashSet等或其他任何工具,例如迭代器。
equals()不起作用...

最佳答案

当您执行arraySubs[j+1]==arraySubs[j]时,您将比较实例ID,而不是值。您应该使用arraySubs[j+1].equals(arraySubs[j])

只需尝试调试您的代码,或运行类似的内容:

for(int j = 0; j < arraySubs.length; j++) {
    if(j<arraySubs.length-1) {
        System.out.println("j:" + j);
        System.out.println("j val:" + arraySubs[j]);
        System.out.println("j+1 val:" + arraySubs[j+1]);
        if(arraySubs[j+1] != null && arraySubs[j+1].equalsIgnoreCase(arraySubs[j])) { // The FIX
            System.out.println("j val changed to null");
            arraySubs[j]=null;
        }
    }
    if(arraySubs[j]!=null) {
        System.out.println(arraySubs[j]);
    } else {
        System.out.println("skipping null");
    }
}

09-07 14:53