我试图了解如何正确使用 EnumSet 来等效于 C# 的标志。这是我的实现和使用它的方法。如您所见,检查标志是否存在无法正常工作。你能告诉我我做错了什么吗?
我有以下带有 EnumSet 的枚举:
public enum ExcelRangeBordersFlag {
BORDER_LEFT,
BORDER_BOTTOM,
BORDER_TOP,
BORDER_RIGHT;
public static final EnumSet<ExcelRangeBordersFlag> SELECTED_BORDERS = EnumSet.noneOf(ExcelRangeBordersFlag.class);
}
(这是否正确实施?)
我现在希望能够做一些事情,比如添加到集合中,并检查集合是否包含一个值。但是,这不起作用:
private static ExcelRangeBordersFlag getBordersFlag(boolean bottom, boolean top, boolean left, boolean right){
ExcelRangeBordersFlag results = null;
if (bottom){
results.SELECTED_BORDERS.add(ExcelRangeBordersFlag.BORDER_BOTTOM);
}
if (top){
results.SELECTED_BORDERS.add(ExcelRangeBordersFlag.BORDER_TOP);
}
if (left){
results.SELECTED_BORDERS.add(ExcelRangeBordersFlag.BORDER_LEFT);
}
if (right){
results.SELECTED_BORDERS.add(ExcelRangeBordersFlag.BORDER_RIGHT);
}
System.out.println(results);
return results;
}
private static void MergeAndWriteToCell(Sheet sh, int sRow, int eRow, int sCell, int eCell, ExcelRangeBordersFlag borders , String text){
CellRangeAddress cellRangeAddress = new CellRangeAddress(sRow, eRow, sCell, eCell);
sh.addMergedRegion(cellRangeAddress);
Row row = sh.getRow(sRow);
Cell cell = row.getCell(sCell);
cell.setCellValue(text);
if (borders.SELECTED_BORDERS.contains(ExcelRangeBordersFlag.BORDER_BOTTOM)){
RegionUtil.setBorderBottom(CellStyle.BORDER_MEDIUM, cellRangeAddress, sh, wb);
System.out.println("Contains bottom.");
}
if (borders.SELECTED_BORDERS.contains(ExcelRangeBordersFlag.BORDER_LEFT)){
RegionUtil.setBorderLeft(CellStyle.BORDER_MEDIUM, cellRangeAddress, sh, wb);
System.out.println("Contains left.");
}
if (borders.SELECTED_BORDERS.contains(ExcelRangeBordersFlag.BORDER_TOP)){
RegionUtil.setBorderTop(CellStyle.BORDER_MEDIUM, cellRangeAddress, sh, wb);
System.out.println("Contains top.");
}
if (borders.SELECTED_BORDERS.contains(ExcelRangeBordersFlag.BORDER_RIGHT)){
RegionUtil.setBorderRight(CellStyle.BORDER_MEDIUM, cellRangeAddress, sh, wb);
System.out.println("Contains right.");
}
System.out.println();
}
最后一种方法显示包含所有 ExcelRangeBorder 类型,即使我执行以下操作:
borders = getBordersFlag(false, false, false, false);
MergeAndWriteToCell(sh, 4,4,1,3, borders, "Percent of Original List Price Received*");
输出:
null
Contains bottom.
Contains left.
Contains top.
Contains right.