简体   繁体   English

方法重复输出

[英]Method duplicates output

Pretty new to sling and Java so I apologize in advance. 吊索和Java很新,所以我提前致歉。 But does anybody have any idea why when I'm at the root it's outputting my path twice? 但是有人知道为什么当我处于根源时会两次输出我的路径吗? It's odd that it only happens at the absolute root. 奇怪的是,它只发生在绝对根上。

public static String generateTest(Page page, Page rootPage, String bc) {

    Page parent = page.getParent();

    String bread = ""; 
    bread += (parent != null) ? "<li><a href=" + parent.getPath() + ">" + parent.getTitle() + "</a>" : "";
    bread += "<li>" + "<a href=" + page.getPath() + ">" + page.getTitle() + "</a></li>" + 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());
}

Any help is greatly appreciated! 任何帮助是极大的赞赏!

First, ifAtRoot() will return true only if page is null because you cannot compare objects (including strings) using == . 首先, ifAtRoot()仅在pagenull时才返回true,因为您不能使用==比较对象(包括字符串)。 You should use .equals() instead: 您应该改用.equals()

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

In your case first call of ifAtRoot() returned false , so you called it second time recursively passing brend that just has been created. 在您的情况下,第一次调用ifAtRoot()返回false ,因此您第二次调用它以递归方式传递刚创建的brend The second call creates brend again and appends bc (that contains previously created brend) to it. 第二个调用再次创建brend ,并向其附加bc (包含先前创建的brend)。 The second call of ifAtRoot() for your luck returns true. 如果需要,第二次调用ifAtRoot()返回true。 Otherwise you'd enter infinite recursion and finish with StackOverflowError . 否则,您将输入无限递归并以StackOverflowError完成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM