插入EnumMaps错误

时间:2019-02-10 06:16:41

标签: java enums

我有一个Vehicle类,其中包含一个枚举Vehicle Type,如下所示

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.
}

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

1 个答案:

答案 0 :(得分:0)

在您的情况下, availEconomy 是实例变量,在Java中,您只能在方法中将值放在实例变量中。否则,您可以定义availEconomy static并将值放在static块内。下面是该代码。

公共类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);
}

}