加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-14 19:21:31 所属栏目:Java 来源:网络整理
导读:将从控制台输入获取的字符串与数组中的字符串进行比较时,除非我添加.toString(),否则它始终为false.两个字符串都相等,它应该在不添加.toString()的情况下工作.任何人都可以帮我找出原因吗? 在这里,我从控制台获取要比较的字符串: System.out.println("nEn

将从控制台输入获取的字符串与数组中的字符串进行比较时,除非我添加.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 listn");

这是删除方法:

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()方法.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读