是否可以根据索引识别对象?

时间:2019-10-23 22:45:52

标签: java oop object

所以可以说我有一个Bus类,并且我有两个bus实例。

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

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

2 个答案:

答案 0 :(得分:0)

我想说,应该用一个ID来标识公共汽车,而不仅仅是因为它是第二个要创建的公共汽车。 因此,假设您添加了一个属性

{ "link": "path/to/image.jpg" }

转到Bus类,并在Bus类中覆盖

private int ID

您可以区分列表中包含的两条公交车

  @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;
  }

答案 1 :(得分:0)

首先,我们自动为公共汽车编号。

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

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

    int getId() {
        return id;
    }
}

我们会在某些地方跟踪总线的创建过程。由于我们要跟踪整数ID号,因此从ID到总线的映射很有用。 (我们也可以使用数组,因为总线号是密集分配的,但是如果总线被销毁和创建,则映射也具有一些优势,因为总线号不再是密集的。)

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 …