不明白为什么一个文档的两个org.w3c.dom.NodeList不相等,而它们的哈希码也不相等。尽管一个节点列表中的每个节点都等于另一个节点列表中的该节点?
// 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
}
当您尝试比较两个对象时,您是在比较引用,而不是值。两者都存在于内存中的不同位置,并且具有不同的地址。因此,当您对它们应用相等运算符时,它会返回 false。 I-E 0xA332CD == 0xB2254F//假