gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 22:34:53 25 4
gpt4 key购买 nike

假设我有一个 Bus 类,并且有两个 Bus 实例。

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

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

最佳答案

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

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

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

listOfBuses.contains(new Bus(userInput))

关于java - 是否可以根据索引来识别对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58531870/

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