我有一个枚举
Customer("Customer"),
BankName("Bank Name"),
AccountNumber("Account Number"),
Amount("Available Amount");
我有一个包含正确顺序的整数数组
private static int[] realOrder;
我有一个按正确的顺序对枚举进行排序的方法
public static void configureColumns(Column... newOrder)
{
realOrder = new int[values().length];
for (Column column : values())
{
realOrder[column.ordinal()] = -1;
boolean isFound = false;
for (int i = 0; i < newOrder.length; i++)
{
if (column == newOrder[i])
{
if (isFound)
{
throw new IllegalArgumentException("Column '" + column.columnName + "' is already configured.");
}
realOrder[column.ordinal()] = i;
isFound = true;
}
}
}
}
当我称之为那种方法时
Column.configureColumns(Column.Amount, Column.AccountNumber, Column.BankName);
我希望它被打印
* Available Amount
* Account Number
* Bank Name
我有一个方法,它根据realOrder索引返回一个链表
public static List<Column> getVisibleColumns()
{
List<Column> result = new LinkedList<>();
int index;
for(int i = 0; i < realOrder.length; i++)
{
if(realOrder[i]!=-1)
{
index = realOrder[i];
result.add(index, Column.values()[index]);
}
}
return result;
}
但我得到java.lang.IndexOutOfBoundsException: Index: 2, Size: 0
,因为我应该从0开始填充数组。如果我将realOrder数组从最小到最大排序,它可以工作,但不是预期的方式。我该如何解决?
答案 0 :(得分:1)
您似乎希望getVisibleColumns()
完全按照configureColumns()
的方式返回值,那么为什么不记得呢?
public enum Column {
Customer("Customer"),
BankName("Bank Name"),
AccountNumber("Account Number"),
Amount("Available Amount");
private static Column[] realOrder;
private final String columnName;
private Column(String columnName) {
this.columnName = columnName;
}
public String getColumnName() {
return this.columnName;
}
public static void configureColumns(Column... newOrder) {
realOrder = newOrder.clone();
}
public static List<Column> getVisibleColumns() {
return Collections.unmodifiableList(Arrays.asList(realOrder));
}
}
如果您还需要知道特定Column
的订单索引,请不要创建单独的数组来存储它。只需在枚举中添加一个额外的字段:
private int orderIndex = -1;
然后在配置时更新值:
public static void configureColumns(Column... newOrder) {
realOrder = newOrder.clone();
for (Column column : values())
column.orderIndex = -1;
for (int i = 0; i < newOrder.length; i++)
newOrder[i].orderIndex = i;
}