首页 > 解决方案 > 为什么两个具有相似标签的 NodeList 不相等?

问题描述

不明白为什么一个文档的两个 org.w3c.dom.NodeList 不相等并且它们的哈希码不相等。尽管一个 NodeList 中的每个 Node 都等于另一个 NodeList 中的这样的 Node?

    // Parse xml file to Document
    File fXmlFile = new File("src/test/resources/sample.xml");
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document doc = dBuilder.parse(fXmlFile);

    // Get cais Nodes
    XPath xpath = XPathFactory.newInstance().newXPath();
    NodeList caisNodes = (NodeList) xpath.evaluate("//c[@n='CAIS']/s", doc, XPathConstants.NODESET);
    NodeList caisNodes2 = (NodeList) xpath.evaluate("//c[@n='CAIS']/s", doc, XPathConstants.NODESET);

    System.out.println(caisNodes.hashCode() == caisNodes2.hashCode()); //false
    System.out.println(caisNodes.equals(caisNodes2)); //false
    for (int i = 0; i < caisNodes.getLength(); i++) {
System.out.println(caisNodes.item(i).equals(caisNodes2.item(i))); // all true 
System.out.println(caisNodes.item(i).hashCode()==caisNodes2.item(i).hashCode()); // all true
    }

标签: hashcodenodelist

解决方案


当您尝试比较两个对象时,您是在比较引用,而不是值。这两者都存在于内存内部的不同位置并且具有不同的地址。因此,当您对它们应用相等运算符时,它会返回 false。IE 0xA332CD == 0xB2254F // 假


推荐阅读