![](/img/trans.png)
[英]Is it possible to identify that object is collected by garbage collector or not in java?
[英]Is it possible to identify an object based on an index?
所以假設我有一個 class 總線,我有兩個總線實例。
Bus bus1 = new Bus(); Bus bus2 = new Bus();
現在,如果我提示用戶輸入索引,假設他輸入 2。我如何驗證 bus2 是否存在?
我會說 Bus 應該由 ID 標識,而不僅僅是因為它是要創建的第二個。 所以假設你添加一個屬性
private int ID
到總線 class 並覆蓋總線 class,
@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))
首先,我們自動為我們的巴士編號。
class Bus {
private static int lastId = 0;
int id;
Bus() {
id = ++lastId; // assign unique bus id
}
int getId() {
return id;
}
}
我們在某個地方跟蹤我們的公共汽車,因為它們是創建的。 由於我們想通過 integer id 編號進行跟蹤,因此從 id 到總線的 map 很有用。 (我們也可以使用數組,因為總線編號是密集分配的,但是如果總線被破壞和創建,map 具有一些優勢,因為總線編號不再一定是密集的)。
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 …
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.