定義類別
class Category
{
private String name = "";
private List<Category> children = new ArrayList<>();
private Category parent = null;
public Category(String name)
{
this.name = name;
}
public void addChild(Category child)
{
child.parent = this;
children.add(child);
}
public Collection<Category> children()
{
return new HashSet<>(children);
}
public Category parent()
{
return parent;
}
public String toString(){return name;}
public String entireHierarchyToString()
{
return entireHierarchyToString(0);
}
private String entireHierarchyToString(int d)
{
String tmp = "";
for(int i=0;i<d;i++)
tmp += "\t";
tmp += name;
for(Category c : children)
tmp += "\n" + c.entireHierarchyToString(d+1);
return tmp;
}
}
然後我們使用遞歸方法爲我們構建樹:
private void process(String[] path, int p, Category root)
{
if(p >= path.length)
return;
String tmp = path[p];
Category next = null;
for(Category c : root.children()) {
if (c.toString().equals(tmp)) {
next = c;
break;
}
}
if(next == null) {
next = new Category(tmp);
root.addChild(next);
}
process(path, p+1, next);
}
在我們的主要方法,那麼我們可以使用下面的邏輯:
List<String> folders = new ArrayList<String>();
folders.add("Buffet:soups:veg soup");
folders.add("Buffet:soups:non veg soup");
folders.add("Buffet:soups:non veg soup:chicken soup");
folders.add("Vegetables");
folders.add("Cheese");
folders.add("Buffet:Starters");
folders.add("Buffet:Sandwitch");
folders.add("Buffet:Sandwitch:Cheese Sandwitch");
folders.add("Buffet:soups:veg soup:tomato soup");
Category root = new Category("[ROOT]");
for(String s : folders)
{
process(s.split(":"), 0, root);
}
System.out.println(root.entireHierarchyToString());
這應該打印出來:
[ROOT]
Buffet
soups
veg soup
tomato soup
non veg soup
chicken soup
Starters
Sandwitch
Cheese Sandwitch
Vegetables
Cheese
爲什麼你只是不一起工作的定義,一個類模型代替字符串? –
我需要拆分字符串,以便區分類別和子類別。 –