java - 插入 EnumMaps 错误
问题描述
我有一个包含枚举车辆类型的车辆类,如下所示
public abstract class Vehicle{
public enum VehicleType
{
ECONOMY, COMPACT, SUV;
}
//method variables..getters and setters below
}
我现在在另一个名为 CarReservation 的类中工作,并且无法将值插入 enumMap 以跟踪库存,如下所示
import packageName.Vehicle.*;
import packageName.VehicleType;
public class CarReservation {
/*public enum VehicleType
{
//ECONOMY, COMPACT, SUV;
}*/
//do I need to include the enum in this class as well?
public static final int MAX_ECONOMY = 10;
public static final int MAX_SEDAN = 5;
public static final int MAX_SUV = 5;
Map<VehicleType, Integer> availEconomy = new EnumMap<VehicleType, Integer>(VehicleType.class);
availEconomy.put(VehicleType.ECONOMY, MAX_ECONOMY); //Eclipse gives me an error saying constructor header name expected here.
}
我正在尝试为不同的车辆类型创建一种跟踪计数的方法。有人可以告诉我我的方法有什么问题吗?谢谢!
解决方案
在您的情况下, availEconomy是实例变量,而在 java 中,您只能在方法中将值放入实例变量中。否则您可以定义availEconomy 静态并将值放入静态块中。下面是代码。
公共类 CarReservation {
/*
* public enum VehicleType { //ECONOMY, COMPACT, SUV; }
*/
// do I need to include the enum in this class as well?
public static final int MAX_ECONOMY = 10;
public static final int MAX_SEDAN = 5;
public static final int MAX_SUV = 5;
static Map<VehicleType, Integer> availEconomy = new EnumMap<VehicleType, Integer>(VehicleType.class);
static {
availEconomy.put(VehicleType.ECONOMY, MAX_ECONOMY);
}
}
推荐阅读
- ios - 允许通过 GCDAsyncUdpSocket 在 xcode 9 中为 ios 应用程序列出 udp 端口
- epplus - epplus 中的工作表单元格不能操作数“+=”
- c# - 为什么对象在向上转换时会保存属性
- reactjs - 在 dispatch() 我得到一个空数组
- javascript - React:ES8 中的事件处理
- angular - 在 Angular 4 上处理唯一编号验证?
- javascript - 如何将参数传递给 Toaster 的 onClick 事件?
- c++ - 内部获取 MODULEINFO
- servicestack.redis - SignalR Core 与 Redis Pub\Sub 和控制台应用程序
- mysql - 出现 MySQL 错误 #1242