方法重复输出 [英] Method duplicates output

查看:66
本文介绍了方法重复输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对 sling 和 Java 非常陌生,所以我提前道歉.但是有没有人知道为什么当我在根时它正在输出我的路径两次?奇怪的是它只发生在绝对根处.

Pretty new to sling and Java so I apologize in advance. 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());
}

非常感谢任何帮助!

推荐答案

首先,ifAtRoot() 只会在 pagenull 时返回 true> 因为您不能使用 == 比较对象(包括字符串).您应该使用 .equals() 代替:

First, ifAtRoot() will return true only if page is null because you cannot compare objects (including strings) using ==. You should use .equals() instead:

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 结束.

In your case first call of ifAtRoot() returned false, so you called it second time recursively passing brend that just has been created. The second call creates brend again and appends bc (that contains previously created brend) to it. The second call of ifAtRoot() for your luck returns true. Otherwise you'd enter infinite recursion and finish with StackOverflowError.

这篇关于方法重复输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆