我的问题是:这两个功能是否有所不同?我的意思是我知道它们返回的内容有所不同,但是一个元素中的元素数量可能会不同于第二个元素中的元素数量。我会尽力解释。我为我的类(class)之一实现了TreeModel,试图基于JTree在PC上更好地查看文件。所以这是它的一部分:

public Object getChild(Object parent, int index) {
        File[] children = ((File) parent).listFiles();
        if(children == null || index < 0 || index >= children.length) {
            return null;
        }

        File result = new MyFile(children[index]);
        return result;
}

public int getChildCount(Object parent) {
        //---
        //String[] children = ((File)parent).list();
        File[] children = ((File)parent).listFiles();
        //---

        if(children == null) {
            return 0;
        }
        return children.length;
}

我标记了有趣的代码。如果为此注释行更改了这两行,有时加载TreeModel后会得到NullPointerException:jtree.setModel(treeModel);。此未注释不会引起任何麻烦。我检查了文档,发现没有异常,包括两种方法都返回null。这里发生了什么?

最佳答案

两种方法基本相同,请查看http://www.docjar.com/html/api/java/io/File.java.html以获得详细信息。

09-28 10:28
查看更多