in Java I have two functions working together to return a boolean condition. Both are getting objects from a class Programa with inheritance classes Serie and Filme. They should return true only when the oject trying to being created have the same name the same category same class from one already existing, but when I have same name, with same category in other class, he still getting true.
Ex: name: Doe, category COMEDIA, Serie I can't do "name: Doe, category COMEDIA, Filme"
You can see where I'm getting wrong?
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");
}
}
CodePudding user response:
This is what you are doing. When you return true you will not know if it was Filme
or Serie
. Perhaps you should return an int
of 1,2 or -1 or use an enum
to indicate what was evaluated.
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;
}
CodePudding user response:
Is there inheritance between Filme and Serie ? In this case, if a Serie is a Filme (Serie extends Filme) then Serie.class.isInstance(filmeObject) will be false always and Filme.class.isInstance(serieObject) will be true.
The isInstance method decides if the object (argument) is compatible with the class.
The dynamic type of the object is compatible with the Class (static type) if it extends it (static type is a class) or implements it (static type is an interface).