我正在编码树,我需要拆分字符串(例如"java.lang.String"
→"java"
,"lang"
,"String"
)并使用树那些。
以下是我的节点,其中包含ArrayList
个孩子:
public class PackageNode {
String value;
List<PackageNode> children;
PackageNode(String value) {
this.value = value;
children = new ArrayList<>();
}
public boolean isLeaf() {
return children.size() == 0;
}
}
以下是树的add
方法:
public boolean add(String className) {
String[] names = className.split("\\.");
if (names[0].equals("java")) {
if (root == null) {
root = new PackageNode(names[0]);
PackageNode temp = root;
for (int i = 1; i < names.length; i++) {
temp.children.add(new PackageNode(names[i]));
temp = temp.children.get(0);
}
return true;
} else {
PackageNode temp = root;
int i,j;
for (i = 1; i < names.length; i++) {
for (j = 0; j < temp.children.size(); j++) {
if (temp.children.get(j).value.equals(names[i])) {
temp = temp.children.get(j);
break;
}
}
if (j == temp.children.size()) {
temp.children.add(new PackageNode(names[i]));
temp = temp.children.get(j);
}
}
return true;
}
}
return false;
}
以下是我的contains
方法:
public boolean contains(String className) {
String[] names = className.split("\\.");
if (names[0].equals(root.value)) {
PackageNode temp = root;
for (int i = 1; i < names.length; i++) {
for (int j = 0; j < temp.children.size(); j++) {
if (temp.children.get(j).value.equals(names[i])) {
temp = temp.children.get(j);
break;
}
if (j == temp.children.size()-1)
return false;
}
}
return true;
}
return false;
}
我的问题是:
我的代码有什么问题吗?如果是这样,我应该如何更改它?
我需要实施:
public int height()
public int size()
public Iterator<PackageNode> iterator()
你能给我一些帮助/建议吗?