在我的程序中,我已经复制并粘贴了代码(这是一个明显的禁忌),因为我还没有弄清楚如何将我想要的参数传递给这个方法:
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();
}
关于java - 创建一个参数是类和通用 ArrayList 的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15909243/