我有两种几乎完全相同的方法。我想知道是否有办法将这两种方法合并为1,这样我就可以将两种类型的地图作为参数。这些方法写入excel文件。关键是excel标题(所有键都在第一行),映射列表是每个键(数据)下面的所有内容。有什么独特的想法吗?
private void test(Sheet sheet, HashMap<String, List<Double>> map) {
for (String var : map.keySet()) {
int rowNumb=0;
Row row = sheet.getRow(rowNumb);
Cell cell = row.createCell(currColumn);
cell.setCellValue(var);
rowNumb++;
List<Double> list = map.get(var);
for (int i = 0; i < list.size(); i++) {
row = sheet.getRow(rowNumb);
cell = row.createCell(currColumn);
cell.setCellValue(list.get(i));
}
currColumn++;
}
}
private void test(Sheet sheet, HashMap<String, List<String>> map) { <-- takes in String list rather thand Double.
for (String var : map.keySet()) {
int rowNumb=0;
Row row = sheet.getRow(rowNumb);
Cell cell = row.createCell(currColumn);
cell.setCellValue(var);
rowNumb++;
List<String> list = map.get(var); <---- Only thing that is different
for (int i = 0; i < list.size(); i++) {
row = sheet.getRow(rowNumb);
cell = row.createCell(currColumn);
cell.setCellValue(list.get(i));
}
currColumn++;
}
}
答案 0 :(得分:4)
你应该使用泛型:
private <T> void test(Sheet sheet, HashMap<String, List<T>> map) {
for (String var : map.keySet()) {
List<T> list = map.get(var);
for (int i = 0; i < list.size(); i++) {
row = sheet.getRow(i);
cell = row.createCell(currColumn);
cell.setCellValue(list.get(i));
}
currColumn++;
}
}
如果您之前对String
和Double
提出任何引用,请立即放置T
。