DOM代码获取type元素触发NullPointerException及==与equals差异疑问
DOM操作中获取type元素时触发NullPointerException的问题
我在编写DOM相关代码时遇到了奇怪的问题,代码如下:
public Item getItem(String id) throws ConstructorNotDefinedException { //Find the specific item Element we are working with Element item = null; for (int i = 0; i < this.items.getLength(); i++) { //items is a NodeList of all items, derived from the document Element Element currentItem = (Element) this.items.item(i); if (currentItem.getAttribute("id") == id) { //only runs once since every ID is unique item = currentItem; } } //The line with the error Element typeElement = (Element) item.getElementsByTagName("type").item(0); //more code using typeElement... }
主类运行代码如下:
public class test { public static void main(String[] args) throws ConstructorNotDefinedException { ItemDataReader reader = ItemDataReader.newInstance(Paths.get(System.getProperty("user.home"), "Documents", "path", "to", "xml", "document.xml")); Item testItem = reader.getItem("dog"); } }
前半部分代码运行完全正常,但当尝试获取typeElement时触发了NullPointerException,我不清楚该异常的来源。
我使用的XML文档示例如下:
<item id="dog"> <type>1</type> <name>Dog</name> <strength>10</strength> </item> <item id="cat"> <type>1</type> <name>Cat</name> <strength>10</strength> </item>
我尝试了多种方法仍未解决问题,恳请各位提供帮助!
编辑
我采纳了Benjamin W.的建议,使用.equals()方法后问题得以解决,但仍不清楚为何使用==会失效。
问题原因说明
在Java里,==是用来比较对象的内存引用地址,而非字符串的实际内容。currentItem.getAttribute("id")返回的是一个新生成的String对象,和你传入的id参数(比如"dog")虽然内容一致,但属于不同的对象实例,内存地址不相同,所以==判断会返回false,导致item变量始终为null,后续调用item.getElementsByTagName()自然就触发了NullPointerException。
而.equals()方法的作用就是专门比较字符串的内容是否相等,不管两个String对象是不是同一个引用,只要内容匹配就会返回true。所以把判断条件改成currentItem.getAttribute("id").equals(id)就能正确匹配到目标元素,避免item为null的情况。
另外建议增加空值判断,防止getAttribute返回null时调用equals触发新的异常:
if (id != null && id.equals(currentItem.getAttribute("id"))) { item = currentItem; }
内容的提问来源于stack exchange,提问作者Foxler2010
相关产品推荐
相关产品推荐

