使用.equals()的字符串比较在Java中不起作用.

将从控制台输入获取的字符串与数组中的字符串进行比较时,除非我添加.toString(),否则它始终为false.两个字符串都相等,它应该在不添加.toString()的情况下工作.任何人都可以帮我找出原因吗?

在这里,我从控制台获取要比较的字符串:

System.out.println("\nEnter the name you wish to remove from the list.");
String name = in.nextLine();
System.out.println("\n\"" + myNameList.remove(new MyOrderedList(name)) + "\"" + " removed from the name list\n");

这是删除方法

public T remove(T element) {
    T result;
    int index = find(element);

    if (index == NOT_FOUND) {
        throw new ElementNotFoundException("list");
    }

    result = list[index];
    rear--;

    /** shift the appropriate elements */
    for (int scan = index; scan < rear; scan++) {
        list[scan] = list[scan+1];
    }

    list[rear] = null;
    return result;
}

这是find方法,问题是:

private int find(T target) {
    int scan = 0,result = NOT_FOUND;
    boolean found = false;

    if (!isEmpty()) {
        while (!found && scan < rear) {
            if (target.equals(list[scan])) { // Not sure why this does not work until I add the .toString()s
                found = true;
            }
            else {
                scan++;
            }
        }
    }

    if (found) {
        result = scan;
    }
    return result;
}

if(target.equals(list [scan]))总是返回false,除非我将其更改为if(target.toString().equals(list [scan] .toString()).

我使用ArrayList来表示列表的数组实现.列表的前面保留在数组索引0处.如果有帮助,则扩展此类以创建特定类型的列表.如果需要,我可以发布所有课程.

最佳答案
如果myNameList具有String泛型参数,那么这将不起作用,因为没有String将等于MyOrderedList的类型.

如果myNameList具有MyOrderedList泛型参数,那么您需要确保为其定义equals()方法.

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...