【问题标题】:Is it possible to identify an object based on an index?是否可以根据索引识别对象?
【发布时间】:2019-10-23 22:45:52
【问题描述】:

假设我有一个总线类,我有两个总线实例。

Bus bus1 = new Bus(); Bus bus2 = new Bus();

现在如果我提示用户输入索引,假设他输入 2。我如何验证 bus2 是否存在?

【问题讨论】:

  • 您将需要一种方法来找到指示的总线,这本身就解决了存在问题。粗略地说,您可以写“如果用户输入 1,则使用 bus1,否则如果 2,则使用 bus2,否则它不存在”。但是为每条总线使用不同的命名变量并不是正确的方法。您需要将总线存储在可以通过 id 检索的集合中 - 比如说一个数组(如果 id 密集)或一个集合。

标签: java oop object


【解决方案1】:

我会说 Bus 应该由 ID 来标识,而不仅仅是因为它是要创建的第二个。 所以假设你添加一个属性

private int ID

到 Bus 类并在 Bus 类中覆盖

  @Override
  public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + ID;
    return result;
  }

  @Override
  public boolean equals(Object obj) {
    if (this == obj)
      return true;
    if (obj == null)
      return false;
    if (getClass() != obj.getClass())
      return false;
    Bus other = (Bus) obj;
    if (ID != other.ID)
      return false;
    return true;
  }

您可以区分列表中包含的两个总线

listOfBuses.contains(new Bus(userInput))

【讨论】:

  • 对于要在 listOfBuses 中找到的新总线,id 大致相同。因此,您有两个具有相同 id 的 Bus 对象,并且 id 不再是唯一的。当然,您可以区分“真实总线”和“假查找临时总线”(如此处),但这似乎不太好。
【解决方案2】:

首先我们会自动给公交车编号。

class Bus {
    private static int lastId = 0;
    int id;

    Bus() {
       id = ++lastId; // assign unique bus id
    }

    int getId() {
        return id;
    }
}

我们在某处跟踪我们创建的巴士。由于我们想通过整数 id 编号进行跟踪,因此从 id 到 bus 的映射很有用。 (我们也可以使用数组,因为公交车号被密集分配,但如果公交车被销毁和创建,地图有一些优势,因为公交车号不再一定密集)。

Map<Integer, Bus> busMap = new HashMap<>();

bus = new Bus(); // 1
busMap.put(bus.getId(), bus);

bus = new Bus(); // 2
busMap.put(bus.getId(), bus);

现在检索/验证总线(假设用户在 int b 中输入):

   bus = busMap.get(b);
   if (bus == null) 
      … then b is not a valid bus id …

   … otherwise we have the bus we wanted …

【讨论】:

    猜你喜欢
    • 2022-11-16
    • 1970-01-01
    • 2021-12-30
    • 1970-01-01
    • 2011-10-10
    • 1970-01-01
    • 2023-01-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多