方法重复输出

对吊索和Java很新,所以我提前道歉。 但有没有人知道为什么当我在根部它输出我的路径两次? 奇怪的是它只发生在绝对根。

public static String generateTest(Page page, Page rootPage, String bc) { Page parent = page.getParent(); String bread = ""; bread += (parent != null) ? "
  • " + parent.getTitle() + "" : ""; bread += "
  • " + "" + page.getTitle() + "
  • " + bc; return (ifAtRoot(parent , rootPage)) ? breadcrumb : generateTest(parent, rootPage, bread); } public static boolean ifAtRoot(Page page, Page root) { return (page == null || root.getPath() == page.getPath()); }

    任何帮助是极大的赞赏!

    首先, ifAtRoot()仅在pagenull时才返回true,因为您无法使用==比较对象(包括字符串)。 您应该使用.equals()代替:

     public static boolean ifAtRoot(Page page, Page root) { return (page == null || root.getPath().equals(page.getPath())); } 

    在你的情况下, ifAtRoot()第一次调用返回false ,所以你第二次调用它来递归传递刚刚创建的brend 。 第二个调用再次创建brend并将bc (包含先前创建的brend)附加到它。 ifAtRoot()的第二次调用将返回true。 否则,您将进入无限递归并使用StackOverflowError完成。