gpt4 book ai didi

java - 将包/类名称列表转换为父/子数据结构

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:02:12 25 4
gpt4 key购买 nike

我有一个类名列表如下:

   String s1 = "com.mycompany.project.dao.hibernate.BaseDAOHibernate";
String s2 = "com.mycompany.project.domain.Product";
String s3 = "com.mycompany.project.domain.ProductCategory";
String s4 = "com.mycompany.project.service.impl.ProductServiceImpl";
String s5 = "com.mycompany.project.domain.User";
String s6 = "com.mycompany.project.service.impl.ProductCategoryServiceImpl";
String s7 = "com.mycompany.project.dao.hibernate.ProductCategoryDAOHibernate";
String s8 = "com.mycompany.project.dao.hibernate.ProductDAOHibernate";

String[] strings = { s1, s2, s3, s4, s5, s6, s7, s8};

我想使用以下类定义将此数组转换为树结构:

public class Item  {
private String itemName;
private List<Item> subItems;

}

该方法将获取上面的数组并生成以下对象。

item.ItemName = "com";
item.suItems = {"mycompany"};

item2.itemName = "mycompany";
item2.subItems = {"project");

item3.itemName = {"project"};
item3.subItems = {"dao", "domain", "service"}

...等等。

请告知如何执行此操作,因为我可能有数百个类的列表作为输入。

谢谢

最佳答案

请参阅我在 C# 上的实现,对于 Java,您可以将其用作伪代码。

public class Item
{
private String itemName;
private List<Item> subItems = new List<Item>();

public void Push(string[] namespaces, int index)
{
if (index >= namespaces.Length)
return;

foreach (Item child in subItems)
{
if (child.itemName == namespaces[index])
{
child.Push(namespaces, index + 1);
return;
}
}

Item newChild = new Item();
newChild.itemName = namespaces[index];
newChild.Push(namespaces, index + 1);
subItems.Add(newChild);
}
}

private static void Namespaces()
{
String s1 = "com.mycompany.project.dao.hibernate.BaseDAOHibernate";
String s2 = "com.mycompany.project.domain.Product";
String s3 = "com.mycompany.project.domain.ProductCategory";
String s4 = "com.mycompany.project.service.impl.ProductServiceImpl";
String s5 = "com.mycompany.project.domain.User";
String s6 = "com.mycompany.project.service.impl.ProductCategoryServiceImpl";
String s7 = "com.mycompany.project.dao.hibernate.ProductCategoryDAOHibernate";
String s8 = "com.mycompany.project.dao.hibernate.ProductDAOHibernate";

String[] strings = { s1, s2, s3, s4, s5, s6, s7, s8 };

Item root = new Item();
foreach (string s in strings)
{
root.Push(s.Split('.'), 0);
}
// Do something with root variable.
}

我还建议使用 HashMap 而不是列表。

关于java - 将包/类名称列表转换为父/子数据结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16811912/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com