假设我有一个类总线,我有两个总线实例。
Bus bus1 = new Bus(); Bus bus2 = new Bus();
现在,如果我提示用户对索引感兴趣,假设他输入了2。我如何验证bus2是否存在?
发布于 2019-10-24 06:56:56
我要说的是,总线应该通过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))发布于 2019-10-24 07:57:26
首先,我们自动给公交车编号。
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 …https://stackoverflow.com/questions/58531870
复制相似问题