java.util.List 找不到元素

标签 java list object search

由于我遇到以下问题,需要再次咨询您:

为了向我的所有项目提供日志记录功能,我使用一个自制的日志记录库,其中包括用于从所有类和对象访问的静态方法,以及在退出时将日志内容转储到文件的功能。这多年来一直运行良好,现在我需要扩展该库以提供使用多个“日志 channel ”的功能,每个“日志 channel ”代表单独的日志。每个日志 channel 都是“Log”类的一个实例(见下文),然后添加到列表中(如类 ListTest3 中,见下文)。但是,当尝试通过创建具有相同 channel 名称的虚拟对象从列表中获取特定日志时,总是返回-1,表示找不到对象。为什么?

类日志:

public class Log {
  //...

  public String getChannel(){
    return channel;
  }

  //...

  public boolean equals(Log compare){
    // return getChannel().equals(compare.getChannel());
    return true;

    /**
     * used to contain a method to compare the channel names of the log
     * object itself and the provided object for comparison, now always
     * returns true for debugging purposes
     */
  }

  //...
}

为了调试,我创建了以下类 ListTest3:

package test;

import java.util.List;
import java.util.LinkedList;

import logging.Log;

public class ListTest3 {
  public static void main(String[] args){
    List list = new LinkedList();
    Log logDefault = new Log();
    logDefault.setChannel("default");
    Log logAdvanced = new Log();
    logAdvanced.setChannel("advanced");
    Log logDebug = new Log();
    logDebug.setChannel("debug");

    list.add(logDefault);
    list.add(logAdvanced);
    list.add(logDebug);

    System.out.println("Index of logDefault: " + list.indexOf(logDefault));
    System.out.println("Index of logAdvanced: " + list.indexOf(logAdvanced));
    System.out.println("Index of logDebug: " + list.indexOf(logDebug));

    Log logDefaultDummy = new Log();
    logDefaultDummy.setChannel("default");
    System.out.println("Index of logDefaultDummy: " + list.indexOf(logDefaultDummy));

    Log logAdvancedDummy = new Log();
    logAdvancedDummy.setChannel("advanced");
    System.out.println("Index of logAdvancedDummy: " + list.indexOf(logAdvancedDummy));

    Log logDebugDummy = new Log();
    logDebugDummy.setChannel("debug");
    System.out.println("Index of logDebugDummy: " + list.indexOf(logDebugDummy));
  }
}

但是,当通过虚拟对象搜索列表时,不会返回三个日志对象的索引,而是始终返回 -1,如以下输出所示:

Index of logDefault: 0
Index of logAdvanced: 1
Index of logDebug: 2
Index of logDefaultDummy: -1
Index of logAdvancedDummy: -1
Index of logDebugDummy: -1

非常感谢任何帮助,因为我不知道如何解决这个问题。感谢您阅读这批文字! ;)

最佳答案

您尚未正确重写 Object 中的 equals()hashCode()。请注意,该方法的正确签名是

public boolean equals(Object o)

而不是

public boolean equals(Log o)

当您打算重写/实现某个方法时,应始终在该方法上使用@Override 注释。这可以避免像您所做的那样的错误。

此外,您正在重新发明轮子。为什么不使用真正的、经过实战检验的、高效的日志框架,例如 logback 或 log4j?

关于java.util.List 找不到元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31265493/

相关文章:

javascript - Vue.js 相当于 data_get php

java - 在java web服务中执行多个线程

java - 提交表单数据后出现以下问题

java - 无法调用正确的数据

linq - “等于”和“顺序等于”之间的区别?

for 中的 Javascript 动态事件

javascript - React - 使用 setState 更新状态中的对象数组

Java hmac 算法无法正常工作

java - 对集合进行单元测试的最佳方法?

python - 在python中将多个数组加在一起形成一个数组