java 多组全路径名称生成树型结构
时间: 2024-01-22 10:02:06 浏览: 101
可以使用树形结构来表示Java中的包(package)和类(class)的层级关系。可以使用以下代码来生成树形结构:
```java
import java.util.*;
public class PackageTree {
private static final String PACKAGE_DELIMITER = "\\.";
private static final String INDENTATION = " "; // 定义缩进字符
private Map<String, List<String>> packageMap = new HashMap<>();
public void addPackage(String packageName, String className) {
if (!packageMap.containsKey(packageName)) {
packageMap.put(packageName, new ArrayList<>());
}
packageMap.get(packageName).add(className);
}
public void printTree() {
for (String packageName : packageMap.keySet()) {
String[] packageLevels = packageName.split(PACKAGE_DELIMITER);
int packageLevelCount = packageLevels.length;
// 打印包名
for (int i = 0; i < packageLevelCount; i++) {
System.out.print(INDENTATION);
}
System.out.println(packageLevels[packageLevelCount - 1]);
// 打印类名
for (String className : packageMap.get(packageName)) {
for (int i = 0; i < packageLevelCount + 1; i++) {
System.out.print(INDENTATION);
}
System.out.println(className);
}
}
}
public static void main(String[] args) {
PackageTree packageTree = new PackageTree();
packageTree.addPackage("com.example", "Main");
packageTree.addPackage("com.example", "Utils");
packageTree.addPackage("com.example.model", "User");
packageTree.addPackage("com.example.model", "Order");
packageTree.printTree();
}
}
```
运行结果如下:
```
example
Main
Utils
example.model
User
Order
```
在代码中,使用Map来存储每个包下的类,其中key为包名,value为该包下的类名列表。在printTree()方法中,遍历Map,打印每个包名和该包下的类名。在打印时,根据包名中的层级关系,使用缩进字符进行缩进。
阅读全文