用好 Java 中的枚举,让你的工作效率飞起来!

// Methods that set and get the status variable.

}

下面这段代码展示它是如何 work 的:

@Test

public void givenPizaOrder_whenReady_thenDeliverable() {

Pizza testPz = new Pizza();

testPz.setStatus(Pizza.PizzaStatus.READY);

assertTrue(testPz.isDeliverable());

}

6.EnumSet and EnumMap


6.1. EnumSet

EnumSet 是一种专门为枚举类型所设计的 Set 类型。

HashSet相比,由于使用了内部位向量表示,因此它是特定 Enum 常量集的非常有效且紧凑的表示形式。

它提供了类型安全的替代方法,以替代传统的基于int的“位标志”,使我们能够编写更易读和易于维护的简洁代码。

EnumSet 是抽象类,其有两个实现:RegularEnumSetJumboEnumSet,选择哪一个取决于实例化时枚举中常量的数量。

在很多场景中的枚举常量集合操作(如:取子集、增加、删除、containsAllremoveAll批操作)使用EnumSet非常合适;如果需要迭代所有可能的常量则使用Enum.values()

publicclass Pizza {

privatestatic EnumSet undeliveredPizzaStatuses =

EnumSet.of(PizzaStatus.ORDERED, PizzaStatus.READY);

private PizzaStatus status;

publicenum PizzaStatus {

}

public boolean isDeliverable() {

returnthis.status.isReady();

}

public void printTimeToDeliver() {

System.out.println("Time to delivery is " +

this.getStatus().getTimeToDelivery() + " days");

}

public static List getAllUndeliveredPizzas(List input) {

return input.stream().filter(

(s) -> undeliveredPizzaStatuses.contains(s.getStatus()))

.collect(Collectors.toList());

}

public void deliver() {

if (isDeliverable()) {

PizzaDeliverySystemConfiguration.getInstance().getDeliveryStrategy()

.deliver(this);

this.setStatus(PizzaStatus.DELIVERED);

}

}

// Methods that set and get the status variable.

}

下面的测试演示了展示了 EnumSet 在某些场景下的强大功能:

@Test

public void givenPizaOrders_whenRetrievingUnDeliveredPzs_thenCorrectlyRetrieved() {

  • 5
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值