首页 > 解决方案 > 插入 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.
}

我正在尝试为不同的车辆类型创建一种跟踪计数的方法。有人可以告诉我我的方法有什么问题吗?谢谢!

标签: javaenums

解决方案


在您的情况下, 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);
}

}


推荐阅读