在 Java 中,我有兩個函式一起作業來回傳一個布爾條件。兩者都從具有繼承類 Serie 和 Filme 的類 Programa 獲取物件。只有當嘗試創建的物件具有相同的名稱 相同的類別 來自一個已經存在的類的相同類時,它們才應該回傳 true,但是當我具有相同的名稱,在其他類中具有相同的類別時,他仍然會得到 true。
例如:名稱:Doe,類別喜劇,意甲我不能做“名稱:Doe,類別喜劇,電影”
你能看出我哪里出錯了嗎?
public boolean seExiste(Programa programa) {
for (Programa y : this.programa) {
if (Serie.class.isInstance(y) && y.getNome().equals(programa.nome)
&& y.getCategoria().equals(programa.categoria)) {
return true;
} if (Filme.class.isInstance(y) && y.getNome().equals(programa.nome)
&& y.getCategoria().equals(programa.categoria)) {
return true;
}
}
return false;
}
public void cadastrar(Programa programa) {
if (!seExiste(programa)) {
// System.out.println(programa.hashCode());
this.programa.add(programa);
} else {
System.err.println("ERROR");
}
}
uj5u.com熱心網友回復:
這就是你正在做的。當您回傳 true 時,您將不知道它是Filme還是Serie。也許您應該回傳int1,2 或 -1 的 an 或使用 anenum來指示評估的內容。
public boolean seExiste(Programa programa) {
for (Programa y : this.programa) {
// here is the common condition.
// this must be true to return true.
// otherwise the loop continues. Notice the ! that inverts the expression.
if (!(y.getNome().equals(programa.nome)
&& y.getCategoria().equals(programa.categoria))) {
continue; // skip next if and continue loop
}
// if the the categoria and nome match then check the instance.
if (Filme.class.isInstance(y) || Serie.class.isInstance(y)) {
return true;
}
}
return false;
}
uj5u.com熱心網友回復:
Filme和Serie之間有繼承嗎?在這種情況下,如果 Serie 是 Filme(Serie extends Filme),那么 Serie.class.isInstance(filmeObject) 將始終為 false,而 Filme.class.isInstance(serieObject) 將為 true。
該isInstance方法決定如果物件(自變數)是與類兼容。
物件的動態型別與類(靜態型別)兼容,如果它擴展它(靜態型別是一個類)或實作它(靜態型別是一個介面)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/326517.html
