创建一个方法,其参数是一个类和一个通用的ArrayList

Dav*_*ell 1 java methods class arraylist object

我的程序我有复制和粘贴代码(一个明显的禁忌)因为我还没有弄清楚如何将我想要的参数传递给这个方法:

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

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

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

我该怎么做呢?

Kep*_*pil 8

你可以这样做:

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;
}
Run Code Online (Sandbox Code Playgroud)

编辑

我刚刚意识到你甚至没有使用第一个参数,正如@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();
}
Run Code Online (Sandbox Code Playgroud)