public class Menu implements Comparable<Menu>{
private int mid;
private String name;
private TreeSet<Menu> childMenu;
private Menu parent;
public Menu(int mid, String name){
super();
this.mid = mid;
this.name = name;
//假设每个人都有子菜单,防止出现错误
childMenu=new TreeSet<Menu>();}
public int getMid(){return mid;}
public void setMid(int mid){
this.mid = mid;}
public String getName(){return name;}
public void setName(String name){
this.name = name;}
public TreeSet<Menu> getChildMenu(){return childMenu;}
public void setChildMenu(TreeSet<Menu> childMenu){
this.childMenu = childMenu;}
public Menu getParent(){return parent;}
public void setParent(Menu parent){
this.parent = parent;}
@Override
public String toString(){return"mid=" + mid + ", name=" + name + ", childMenuNum=" + childMenu.size() + ", parent=" + parent.getName();}
@Override
public int hashCode(){return Objects.hash(mid,name);}
@Override
public boolean equals(Object obj){if(this == obj)returntrue;if(obj == null)returnfalse;
Menu other =(Menu) obj;
if(this.getMid()==other.getMid()&&this.getName().equals(other.getName()))returntrue;returnfalse;}
@Override
public int compareTo(Menu o){
// TODO Auto-generated method stub
return this.mid-o.mid;}}
public class MenuUtil {
public static void show(Menu menu){
show(menu,0);}
// 显示本级及下级所有菜单信息
public static void show(Menu menu,int n){
if(menu==null)
throw new RuntimeException("空指针异常");
for(int i=0;i<n;i++)
System.out.print("\t");
// 显示本级信息
System.out.println(menu.toString());
// 得到下级信息
TreeSet<Menu> set1 =(TreeSet<Menu>) menu.getChildMenu();for(Menu s : set1){
show(s,n+1);}}
// 给指定菜单添加直接子菜单
public static void add(Menu menu, Menu child){
// 得到子菜单
TreeSet<Menu> set1 =(TreeSet<Menu>) menu.getChildMenu();
// 添加子菜单
if(menu.getMid()< child.getMid())
throw new RuntimeErrorException(null, "mid比父类的mid大");if(set1.add(child)== false){
throw new RuntimeErrorException(null, "menu重复");}
// 设置子菜单的父类
child.setParent(menu);}
// 删除子菜单
public static Menu delete(Menu menu, int mid){
// 得到子菜单
TreeSet<Menu> set1 =(TreeSet<Menu>) menu.getChildMenu();for(Menu s : set1){if(s.getMid()== mid){
set1.remove(s);return s;}}return null;}}
public class MenuTest {
public static void main(String[] args){
//定级菜单
Menu m=new Menu(10,null);
//一级菜单
Menu m1=new Menu(9,"child1");
Menu m4=new Menu(8,"child4");
Menu m5=new Menu(7,"child5");
//二级菜单
Menu m2=new Menu(5,"child2");
//三级菜单
Menu m3=new Menu(3,"child3");
//设置m2,m4为m1的子节点
TreeSet<Menu> set1=new TreeSet<>();
set1.add(m2);
set1.add(m4);
m1.setParent(m);
m4.setParent(m1);
m1.setChildMenu(set1);
//设置m3为m2的子节点
TreeSet<Menu> set2=new TreeSet<>();
set2.add(m3);
m2.setParent(m1);
m2.setChildMenu(set2);
m3.setParent(m2);
//显示第一级菜单
System.out.println("查询:");
MenuUtil.show(m1);
System.out.println("添加:");
//添加子菜单
MenuUtil.add(m1, m5);
MenuUtil.show(m1);
//删除子菜单
if(MenuUtil.delete(m1, 7)!=null){
System.out.println("删除成功!");}else{
System.out.println("删除失败!");}
System.out.println("删除:");
MenuUtil.show(m1);}}