使用java写一个分类列表的接口
时间: 2024-04-10 15:28:36 浏览: 16
当然可以!下面是一个示例的分类列表接口的Java代码:
```java
import java.util.ArrayList;
import java.util.List;
public class Category {
private int id;
private String name;
private Integer parentId;
private List<Category> children;
// 构造函数
public Category(int id, String name, Integer parentId) {
this.id = id;
this.name = name;
this.parentId = parentId;
this.children = new ArrayList<>();
}
// Getters and Setters
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getParentId() {
return parentId;
}
public void setParentId(Integer parentId) {
this.parentId = parentId;
}
public List<Category> getChildren() {
return children;
}
public void setChildren(List<Category> children) {
this.children = children;
}
// 添加子分类
public void addChild(Category child) {
children.add(child);
}
}
public class CategoryApi {
private List<Category> categories;
// 构造函数
public CategoryApi() {
this.categories = new ArrayList<>();
initializeCategories();
}
// 初始化分类数据
private void initializeCategories() {
categories.add(new Category(1, "电子产品", null));
categories.add(new Category(2, "手机", 1));
categories.add(new Category(3, "电视", 1));
categories.add(new Category(4, "家具", null));
categories.add(new Category(5, "沙发", 4));
}
// 获取分类列表
public List<Category> getCategoryList() {
List<Category> rootCategories = new ArrayList<>();
for (Category category : categories) {
if (category.getParentId() == null) {
rootCategories.add(category);
} else {
Category parentCategory = findCategoryById(category.getParentId());
if (parentCategory != null) {
parentCategory.addChild(category);
}
}
}
return rootCategories;
}
// 根据id查找分类
private Category findCategoryById(int id) {
for (Category category : categories) {
if (category.getId() == id) {
return category;
}
}
return null;
}
}
// 测试接口
public class Main {
public static void main(String[] args) {
CategoryApi categoryApi = new CategoryApi();
List<Category> categoryList = categoryApi.getCategoryList();
for (Category category : categoryList) {
printCategory(category, 0);
}
}
// 递归打印分类树
private static void printCategory(Category category, int level) {
StringBuilder indent = new StringBuilder();
for (int i = 0; i < level; i++) {
indent.append(" ");
}
System.out.println(indent.toString() + "- " + category.getName());
for (Category child : category.getChildren()) {
printCategory(child, level + 1);
}
}
}
```
这个接口使用了一个示例的分类列表数据,并提供了两个类:`Category`和`CategoryApi`。
`Category`类表示一个分类,包含`id`、`name`、`parentId`和子分类列表`children`属性。它还提供了添加子分类的方法`addChild`。
`CategoryApi`类是分类列表的API,它初始化了示例的分类数据,并提供了一个`getCategoryList`方法来获取分类列表。该方法会将分类数据构建为树形结构,并返回根节点列表。
在示例的`Main`类中,我们测试了接口,使用递归方式打印了分类树。
你可以根据实际需求,将这个示例代码进行修改和扩展。