gpt4 book ai didi

java - 如何使用(对象引用或对象类型)作为 Hashmap 中的值?

转载 作者:行者123 更新时间:2023-12-02 01:15:06 29 4
gpt4 key购买 nike

我正在应对编程挑战,问题如下:

  • 有一个“Vehicle”对象作为“Car”、“Motorcycle”、“Bus”对象的父类,这些子对象中的每一个都有一个 char 类型的 code(id)。
  • 有一个“车库”对象,应该填充车辆数组列表形式的对象,通过将它们的代码作为字符串传递给车库构造函数。例如,以下声明创建了一个包含 2 辆摩托车、一辆汽车和一辆公共(public)汽车的车库:
Garage garage = new Garage ("MMCB")

其中摩托车的代码为“M”,汽车的代码为“C”,巴士的代码为“B”。

所以我创建了一个实用程序类,我将其称为“Garage Service”,它将负责初始化 Garage 以及 Garage 对象的更多操作。

问题是想要创建一个 HashMap ,其中字符串作为键,对象类型作为值,所以我可以使用它为车库构造函数的字符串的每个字符添加一个与该字符串等效的新对象 HashMap 值。我希望我没有详细描述问题,但如果有人可以提供一些帮助,我将不胜感激。

最佳答案

也许这就是你想要的:

import java.util.*;

public class VehicleGarageSample {

interface Vehicle { }

static class Bus implements Vehicle {}

static class Car implements Vehicle {}

static class Motorcycle implements Vehicle {}

//////////////////////////////////////////////////////////////

static class Garage {

private static Map<Character, Class<? extends Vehicle>> vehicleTypeReg = new HashMap<>();

public static void registerVehicleType(Character c, Class<? extends Vehicle> type) {
vehicleTypeReg.put(c, type);
}

//////////////////////////////////////////////////////////////

private Map<Class<? extends Vehicle>, List<Vehicle>> vehicleSlots = new HashMap<>();

private Map<Class<? extends Vehicle>, Integer> vehicleLimits = new HashMap<>();

public Garage(String chars) {
for (char c : chars.toCharArray()) {

Class<? extends Vehicle> vType = vehicleTypeReg.get(c);
if (vType == null) {
throw new IllegalArgumentException("Unknown vehicle type '" + c + "'");
}

// Initialize vehicleSlots
vehicleSlots.computeIfAbsent(vType, k -> new ArrayList<>());

// Initialize vehicleLimits
if (vehicleLimits.containsKey(vType)) {
vehicleLimits.put(vType, vehicleLimits.get(vType) + 1);
} else {
vehicleLimits.put(vType, 1);
}
}
}

public void parkVehicle(Vehicle v) {
Integer limit = vehicleLimits.getOrDefault(v.getClass(), 0);
int parked = vehicleSlots.getOrDefault(v.getClass(), Collections.emptyList()).size();

if (parked >= limit) {
throw new IllegalStateException("No more space for " + v.getClass().getSimpleName());
}

vehicleSlots.get(v.getClass()).add(v);
}
}

//////////////////////////////////////////////////////////////

// How to use Garage
public static void main(String[] args) {

Garage.registerVehicleType('B', Bus.class);
Garage.registerVehicleType('C', Car.class);
Garage.registerVehicleType('M', Motorcycle.class);
// add more if you want

Garage garage = new Garage("MMBC");
garage.parkVehicle(new Motorcycle());
garage.parkVehicle(new Motorcycle());
garage.parkVehicle(new Bus());
garage.parkVehicle(new Car());

garage.parkVehicle(new Car()); // this fails
}
}

关于java - 如何使用(对象引用或对象类型)作为 Hashmap 中的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58775616/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com