在我的程序中,我有复制和粘贴的代码(很明显是不行),因为我还没有弄清楚如何将想要的参数传递给此方法:

public String collectionToFormattedString() {
    String combined = "";
    for (Book b : LibObj.books) {
        combined =  combined + b.toString() + "<br />";
    }
    combined = "<HTML>" + combined +"</HTML>";
    return combined;
}


我想传递参数来执行以下操作:

public String collectionToFormattedString(Object? XYZ, ArrayList ABC) {
    String combined = "";
    for (XYZ b : ABC) {
        combined =  combined + b.toString() + "<br />";
    }
    combined = "<HTML>" + combined +"</HTML>";
    return combined;
}


我该怎么做呢?

最佳答案

您可以这样做:

public <T> String collectionToFormattedString(T XYZ, List<T> ABC) {
    String combined = "";
    for (T b : ABC) {
        combined =  combined + b.toString() + "<br />";
    }
    combined = "<HTML>" + combined +"</HTML>";
    return combined;
}


编辑

我只是意识到您甚至没有使用第一个参数,并且正如@rgettman指出的那样,您没有使用任何T特定的操作,因此您可以将其简化为:

public String collectionToFormattedString(final List<?> list) {
    StringBuilder combined = new StringBuilder("<HTML>");
    for (Object elem : list) {
        combined.append(elem.toString()).append("<br />");
    }
    combined.append("</HTML>");
    return combined.toString();
}

07-28 02:57
查看更多