hashcode - 为什么两个具有相似标签的 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
}
解决方案
当您尝试比较两个对象时,您是在比较引用,而不是值。这两者都存在于内存内部的不同位置并且具有不同的地址。因此,当您对它们应用相等运算符时,它会返回 false。IE 0xA332CD == 0xB2254F // 假
推荐阅读
- android - 打开偏好屏幕后,Android 滚动条出现在视图中
- python - 列 Unknown Firebird Python
- ngxs - NullInjectorError:InjectionToken 窗口没有提供程序
- javascript - 使用 Javascript 有条件地将一段带有 HTML 代码的 Django 模板插入到我的模板中
- spock - 如何在 spock 中组合测试或重用数据
- php - Laravel 高级查询
- r - R Dplyr group_by
- asp.net-core - 如何使用图形 API 在组中搜索用户并返回显示名称?
- vtk - paraview中非结构化网格滤波器的梯度
- django - 得到
在模型字段而不是实际值中